如何在Spring Boot Rest中使用自定义异常?

时间:2016-06-28 23:00:28

标签: 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;
    }
}

EmployeRespository:

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

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

}

的EmployeeService:

@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"
        }
    }
}

问题(S):

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

  2. 任何关于如何进行单元测试的网址都会很棒(连同最好的单元测试库)......

  3. 感谢您抽出宝贵时间阅读本文。

2 个答案:

答案 0 :(得分:3)

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

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

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

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相结合,提供了对控制器进行单元测试所需的方法。

答案 1 :(得分:0)

如果您想知道 EmployeeNotFoundException ,它会被抛出但不会被处理。 您至少需要一个@ExceptionHandler带注释的方法来处理它。

 @ExceptionHandler(EmployeeNotFoundException.class)
        public void handleException(EmployeeNotFoundException  e) {
        // do something
        }

像这样:

 @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;
        }

       @ExceptionHandler(EmployeeNotFoundException.class)
        public void handleException(EmployeeNotFoundException  e) {
         System.out.println("Exception triggered");
        }

    }