SpringBoot中的异常处理

首先自己定义了一个全局的异常处理类

@ControllerAdvice
public class GlobalExceptionHandler {
    public static final String CONTENT_TYPE_FORMED = "application/x-www-form-urlencoded";
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonReturnType doError(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        ex.printStackTrace();
        Map<String, Object> responseData = new HashMap<>();
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            responseData.put("errCode", businessException.getErrCode());
            responseData.put("errMsg", businessException.getMsg());
        } else if (ex instanceof ServletRequestBindingException) {
            //405参数绑定异常
            responseData.put("errCode", EmBussinessError.UNKNOW_ERROR.getErrCode());
            responseData.put("errMsg", "url绑定异常问题");
        } else if (ex instanceof NoHandlerFoundException) {
            //404
            responseData.put("errCode", EmBussinessError.URL_NOT_FOUND.getErrCode());
            responseData.put("errMsg", EmBussinessError.URL_NOT_FOUND.getMsg());
        } else {
            responseData.put("errCode", EmBussinessError.UNKNOW_ERROR.getErrCode());
            responseData.put("errMsg", EmBussinessError.UNKNOW_ERROR.getMsg());
        }
        return CommonReturnType.create(responseData, "fail");

    }
}
  • 关于注解的用法

    • @ControllerAdvice 用来创建一个全局的异常处理类,不用再每个Controller上逐个的定义
    • @ExceptionHandler 用来定义函数针对的异常类型
  • 需要再application.properties中加上配置

    • spring.mvc.throw-exception-if-no-handler-found=true(出现错误时直接报异常)
    • spring.resource.add-mapping=false(关闭工程中资源文件的映射),同时加上这个配置后,静态资源就不能访问了,需要另外配置对静态资源进行映射
    • ServletRequestBindingException :参数绑定异常
    • NoHandlerFoundException:url找不到异常
  • 对静态资源进行映射

@Configuration
public class MyConfig implements WebMvcConfigurer {
    //静态资源的映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");

        registry.addResourceHandler("/templates/**")
                .addResourceLocations("classpath:/templates/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

  • /static/** 访问都映射到classpath:/static/ 目录下
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值