【发布时间】:2017-11-06 14:40:33
【问题描述】:
我想在我的 Rest spring boot 应用程序中处理异常。我知道使用 @ControllerAdvice 和 ResponseEntity 我可以返回一个自定义对象来代表我的错误,但我想要的是在现有异常的主体中添加一个新字段。
我创建了一个自定义异常,它继承了带有额外属性的 RuntimeException,一个字符串列表:
@ResponseStatus(HttpStatus.CONFLICT)
public class CustomException extends RuntimeException {
private List<String> errors = new ArrayList<>();
public CustomException(List<String> errors) {
this.errors = errors;
}
public CustomException(String message) {
super(message);
}
public CustomException(String message, List<String> errors) {
super(message);
this.errors = errors;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
}
在我的控制器中,我只是以这种方式抛出这个自定义异常:
@GetMapping("/appointment")
public List<Appointment> getAppointments() {
List<String> errors = new ArrayList<>();
errors.add("Custom message");
throw new CustomException("This is my message", errors);
}
当我用邮递员测试我的 Rest 端点时,似乎 spring boot 没有编组我的错误字段,响应是:
{
"timestamp": "2017-06-05T18:19:03",
"status": 409,
"error": "Conflict",
"exception": "com.htech.bimaristan.utils.CustomException",
"message": "This is my message",
"path": "/api/agenda/appointment"
}
如果我可以从异常中获取“路径”和“时间戳”字段,我可以使用 @ControllerAdvice 获取自定义对象,但是这两个属性没有 getter。
谢谢。
【问题讨论】:
标签: java spring rest spring-boot exception-handling