如何在 Spring Boot 中以 JSON 形式抛出异常

新手上路,请多包涵

我有一个请求映射 -

   @RequestMapping("/fetchErrorMessages")
  public @ResponseBody int fetchErrorMessages(@RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime) throws Exception
  {
      if(SanityChecker.checkDateSanity(startTime)&&SanityChecker.checkDateSanity(endTime))
      {
          return 0;
      }
      else
      {
          throw new NotFoundException("Datetime is invalid");
      }
  }

如果 startTime 和 endTime 无效,我想抛出 500 错误但返回 JSON 中的异常字符串。但是,我得到一个 HTML 页面而不是说

白标错误页面

此应用程序没有针对 /error 的显式映射,因此您将其视为后备。

2017 年 12 月 20 日星期三 10:49:37 IST

出现意外错误(类型=内部服务器错误,状态=500)。

日期时间无效

我反而想用 JSON 返回 500

 {"error":"Date time format is invalid"}

我该怎么做?

原文由 Prateek Narendra 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 560
2 个回答

假设您有一个自定义异常类 NotFoundException 及其实现如下所示:

 public class NotFoundException extends Exception {

    private int errorCode;
    private String errorMessage;

    public NotFoundException(Throwable throwable) {
        super(throwable);
    }

    public NotFoundException(String msg, Throwable throwable) {
        super(msg, throwable);
    }

    public NotFoundException(String msg) {
        super(msg);
    }

    public NotFoundException(String message, int errorCode) {
        super();
        this.errorCode = errorCode;
        this.errorMessage = message;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    @Override
    public String toString() {
        return this.errorCode + " : " + this.getErrorMessage();
    }
}

现在你想从控制器中抛出一些异常。如果你抛出一个异常,那么你必须从一个标准的错误处理程序类中捕获它,例如在春天他们提供 @ControllerAdvice 注释来申请创建一个类标准错误处理程序。当它应用于一个类时,这个 spring 组件(我的意思是你注释的类)可以捕获从控制器抛出的任何异常。但是我们需要用适当的方法映射异常类。所以我们用你的异常定义了一个方法 NotFoundException 处理程序如下所示。

 @ControllerAdvice
public class RestErrorHandler {

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Object processValidationError(NotFoundException ex) {
        String result = ex.getErrorMessage();
        System.out.println("###########"+result);
        return ex;
    }
}

您想将 http 状态发送到内部服务器 error(500) ,所以这里我们使用了 @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 。由于您使用的是 Spring-boot,因此除了简单的注释 @ResponseBody 可以自动为您完成之外,您不需要制作 json 字符串。

原文由 Ataur Rahman Munna 发布,翻译遵循 CC BY-SA 3.0 许可协议

创建自定义异常。

 public class SecurityException extends RuntimeException {

    private static final long serialVersionUID = -7806029002430564887L;

    private String message;

    public SecurityException() {
    }

    public SecurityException(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

创建自定义响应实体。

 public class SecurityResponse {

    private String error;

    public SecurityResponse() {

    }

    public SecurityResponse(String error) {
        this.error = error;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

}

为自定义异常创建一个带有 ExceptionHandler 的 ControllerAdvice,它将处理自定义异常,填充并返回自定义响应,如下所示。

 @ControllerAdvice
public class SecurityControllerAdvice {

    @ExceptionHandler(SecurityException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public SecurityResponse handleSecurityException(SecurityException se) {
        SecurityResponse response = new SecurityResponse(se.getMessage());
        return response;
    }
}

根据您的情况抛出自定义异常。

 throw new SecurityException("Date time format is invalid");

现在运行并测试你的应用程序。例如:

在此处输入图像描述

原文由 Neeraj Benjwal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题