Spring boot中的异常处理之注解响应

Controller层

return patientRepository.findById(id)
                .orElseThrow(() -> new NotFoundException(String.format("Patient %d not found", id)));

Exception类

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
    public NotFoundException() {
        super();
    }
    public NotFoundException(String message) {
        super(message);
    }
}

Json响应

{
  "timestamp": 1481488691203,
  "status": 404,
  "error": "Not Found",
  "exception": "io.undertree.symptom.exceptions.NotFoundException",
  "message": "Patient 1 not found",
  "path": "/patients/1"
}

总结

还可以使用@ExceptionHandler手动处理异常,并手动设置响应json。

参考:

A Spring Boot Application using Spring Data JPA

评论

暂无评论