Spring MVC中的异常处理 - 异常描述

时间:2016-01-14 07:02:30

标签: java spring rest spring-mvc exception-handling

我有@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

我想在异常中保留异常声明,如果可能的话,我不想在控制器中引入一些异常处理方法。

1 个答案:

答案 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());
}
}