java - 如何使用 Spring Boot Rest 的自定义异常?

标签 java spring rest exception spring-boot

我使用 Spring Boot 连接到 MySQL 5 数据库(通过 JPA)以及服务器端的 Spring Rest。

我的POJO:

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

员工资源库:

@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> {

    Collection<Employee> findByLastName(@Param("name") String name);

}

员工服务:

@RestController
@RequestMapping("/employee")
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @RequestMapping(value = "/findByLastName?{lastName}=", method = RequestMethod.GET)
    Object getEmployees(@PathVariable String lastName) {
        Collection<Employee> result = this.employeeRepository.findByLastName(lastName);
        if (result == null) {
            throw new EmployeeNotFoundException(lastName);
        }
        return result;
    }
}

EmployeeNotFoundException:

public class EmployeeNotFoundException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public EmployeeNotFoundException(String id) {
        super("Could not find Employee " + id);
    }
}

现在,当调用我的 REST API 时,我得到以下结果:

这个在我的数据库中不存在,并且不会抛出 EmployeeNotFoundException:

curl -X GET -H "Content-Type:application/json" http://localhost:8080/employee/search/findByLastName?name="Smith"

结果:

{
    "_embedded" : {
        "employee" : [ ]
    },
    "_links" : {
        "self" : {
            "href" : "http://localhost:8080/employee/search/findByLastName?name=Smith"
        }
    }
}

问题:

  1. 为什么抛出我的 EmployeeNotFoundException?有没有更好的方法来实现这一点(可能还显示 HTTP 状态代码)?

  2. 任何有关如何进行单元测试的 URL 都很棒(以及最好的单元测试库)...

感谢您花时间阅读本文。

最佳答案

这是因为,下面的行不返回 null,而是一个空列表。

Collection<Employee> result = this.employeeRepository.findByLastName(lastName);

您可以检查空列表以及是否抛出异常,或者也只返回空列表。我不建议为查找/搜索抛出异常。我个人只对 getById 这样的 get 方法抛出 NotFoundException 。否则我只是返回空列表。

if (result == null || result.isEmpty()) {
    throw new EmployeeNotFoundException(lastName);
}

此外,修改 Hey-men-wattsup 的代码以发送错误代码,而不是在 Controller 中抛出异常。这将发送 404、NotFound 代码。

@ExceptionHandler(EmployeeNotFoundException.class)
    public void handleException(EmployeeNotFoundException  e, , HttpServletResponse response) {
    response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
}

Spring Boot Test 的 MockMvc 类与 Mockito 相结合,提供了对 Controller 进行单元测试所需的方法。

关于java - 如何使用 Spring Boot Rest 的自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38087620/

相关文章:

java - 如何将字符串返回为json格式

C# Restful客户端-连接超时

php - 使用 REST API 的 PayPal 订单摘要 - - cURL 或 PHP

java - 使用签名不匹配解密 hyperlocal (Google RTB)

java - 通过数据库在两个 Java 应用程序之间同步

java - 如何修改 org.springframework.data.jpa.domain.Specification 对象?

java - 如何停止Spring的默认输出?

rest - 支付 REST API : Large amount causes "instrument declined" error in sandbox

java - Spring Boot无法连接到部署在另一个kubernetes pod上的postgres数据库

java - WSDL 客户端调用失败