我有@ResponseStatus
这样的例外情况:
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY, reason = "Restrioctions violated. Need confirmation.")
@ResponseBody
public class RestrictionExceptions extends Exception {
private List<RestrictionViolation> restrictionViolations;
但是,当引发异常时,只有来自reason
声明的HTTP状态代码和@ResponseStatus
。是否可以在错误响应正文中包含restrictionViolations
?
我想在异常中保留异常声明,如果可能的话,我不想在控制器中引入一些异常处理方法。
答案 0 :(得分:1)
您可以创建一个ErrorResource,其中包含您希望在正文中使用的字段:
public class ErrorResource {
private String reason;
private String value;
private List<RestrictionViolation> restrictionViolations;
....
}
并在处理程序中处理异常:
@ControllerAdvice
public class RestrictionExceptionsHandler {
@ExceptionHandler({ RestrictionExceptions.class })
protected ResponseEntity<ErrorResource> handleInvalidRequest(Exception exception) {
RestrictionExceptions restrictionExceptions = (RestrictionExceptions) exception;
ErrorResource error = new ErrorResource();
Class clazz = exception.getClass();
if(clazz.isAnnotationPresent(ResponseStatus.class)){
ResponseStatus responseStatus = (ResponseStatus) clazz.getAnnotation(ResponseStatus.class);
error.setValue(responseStatus.value());
error.setReason(responseStatus.reason());
}
error.setRestrictionViolations(restrictionExceptions.getRestrictionViolations());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<ErrorResource>(error, error.getValue());
}
}