加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在Rest Service中启动自定义异常

发布时间:2020-12-14 05:36:59 所属栏目:Java 来源:网络整理
导读:我在我的基于 Spring Boot的Rest服务中定义了一个全局异常处理: @ControllerAdvicepublic class GlobalExceptionController { private final Logger LOG = LoggerFactory.getLogger(getClass()); @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR
我在我的基于 Spring Boot的Rest服务中定义了一个全局异常处理:
@ControllerAdvice
public class GlobalExceptionController {

    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR,reason = "Internal application error")
    @ExceptionHandler({ServiceException.class})
    @ResponseBody
    public ServiceException serviceError(ServiceException e) {
        LOG.error("{}: {}",e.getErrorCode(),e.getMessage());
        return e;
    }
}

和一个自定义ServiceException:

public class ServiceException extends RuntimeException {

    private static final long serialVersionUID = -6502596312985405760L;

    private String errorCode;

    public ServiceException(String message,String errorCode,Throwable cause) {
        super(message,cause);
        this.errorCode = errorCode;
    }

    // other constructors,getter and setters omitted
}

到目前为止这么好,当一个异常被触发时,控制器的工作原理和响应:

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

但是字段errorCode不会显示在JSON响应中.

那么如何在我的应用程序中定义一个自定义异常响应.

解决方法

Spring Boot使用 ErrorAttributes的实现来填充渲染为JSON的Map.默认情况下,使用 DefaultErrorAttributes的实例.要包括您的自定义errorCode,您需要提供一个自定义的ErrorAttributes实现,该实现了解ServiceException及其错误代码.此自定义实现应该是您的配置中的@Bean.

一种方法是将DefaultErrorAttributes分类:

@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 ServiceException) {
                errorAttributes.put("errorCode",((ServiceException)error).getErrorCode());
            }
            return errorAttributes;
        }

    };
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读