在身体例外弹簧休息中添加新字段

我想在我的 Rest 弹簧引导应用程序中处理异常。我知道使用@ControllerAdvice和响应实体,我可以返回一个表示我的错误的自定义对象,但我想要的是将一个新字段添加到执行异常的正文中。

我创建了一个自定义异常,该异常继承了具有额外属性的 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);
}

当我使用postman测试我的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"
}

如果可以从异常中获取“path”和“timestamp”字段,则可以使用具有@ControllerAdvice的自定义对象,但是这两个属性没有 getter。

谢谢。


答案 1

井!以下是DefaultErrorAttributes中“path”和“timestamp”的实现,您也可以在自定义实现中执行此操作:

路径:

String path = getAttribute(requestAttributes, "javax.servlet.error.request_uri");
if (path != null) {
    errorAttributes.put("path", path);
}

时间戳:

errorAttributes.put("timestamp", new Date());

有关春季启动中错误自定义的文档,请单击此处

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            // customize here
            return errorAttributes;
        }

   };
}

或者你可以编写一个自定义实现:

@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
        // customize here
        return errorAttributes;
    }
}

Bean 自定义以下错误响应:ErrorAttributes

{
   "timestamp": 1413883870237,
   "status": 500,
   "error": "Internal Server Error",
   "exception": "org.example.ServiceException",
   "message": "somthing goes wrong",
   "path": "/index"
}

可以使用 .@ 可用于跨控制器一般地自定义异常。要在控制器级别进行自定义,可以将它们放在控制器中。"exception"@ExceptionHandlerControlerAdvice

在您的情况下:

   @ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Invalid Inputs")
    @ExceptionHandler(CustomException.class)
    private void errorHanlder() {
        //Log exception
    }


  public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
    Throwable error = getError(requestAttributes);
    if (error instanceof CustomException) {
        errorAttributes.put("errorList", ((CustomException)error).getErrors());
    }
    return errorAttributes;
}

答案 2

以前的答案确实已经存在了所有内容,但不知何故,我花了一段时间才弄清楚,所以总而言之,基本上最简单的方法是拥有这样的豆子:

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
                boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            Throwable error = getError(requestAttributes);
            if (error instanceof CustomExceptionthere) {
                errorAttributes.put("errorList", ((CustomException)error).getErrors());
            }
            return errorAttributes;
        }

    };

推荐