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。