欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot 自定义错误

程序员文章站 2024-01-04 08:04:22
Spring Boot自定义错误信息三种方式:使用`ErrorAttribute`自定义返回错误信息、自定义`ErrorController`处理异常、使用`@ControllerAdvice`&`@ExceptionHandler`配置全局处理异常...

自定义错误信息三种方式:使用ErrorAttribute自定义返回错误信息、自定义ErrorController处理异常、使用@ControllerAdvice&@ExceptionHandler配置全局处理异常

编写Controller类:

    @RequestMapping("exception")
    public Map<String,Object> exception() throws Exception {
        throw new Exception("发成异常");
    }

1.使用ErrorAttribute自定义返回错误信息,个人觉得适合用于处理API接口错误

添加ErrorAttribute配置类:

@Configuration
public class MyErrorAttribute extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String,Object> attributes = super.getErrorAttributes(webRequest,includeStackTrace);
        attributes.put("code","-1");
        attributes.put("message","发生异常");
        return attributes;
    }
}

使用Postman测试结果:
Spring Boot 自定义错误

2.使用自定义ErrorController处理异常

@Controller
public class MyErrorController implements ErrorController {
    private static final String ERROR_PATH = "/error";
    private ErrorAttributes errorAttributes;
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
    @Autowired
    public MyErrorController(ErrorAttributes errorAttributes){
        this.errorAttributes = errorAttributes;
    };

    @RequestMapping(value = ERROR_PATH,produces = "text/html")
    @ResponseBody
    public String errorPageHandler(HttpServletRequest request, HttpServletResponse response){
        ServletWebRequest requestAttributes =  new ServletWebRequest(request);
        Map<String, Object> attr = this.errorAttributes.getErrorAttributes(requestAttributes, false);
        attr.put("code","-2");
        attr.put("message","发生异常");
        return JSONObject.toJSONString(attr);
    }

    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public Map<String, Object> errorApiHandler(HttpServletRequest request){
        ServletWebRequest requestAttributes = new ServletWebRequest(request);
        Map<String, Object> attr=this.errorAttributes.getErrorAttributes(requestAttributes, false);
        attr.put("code","-2");
        attr.put("message","发生异常");
        return attr;
    }
}

Postman测试结果
Spring Boot 自定义错误
浏览器测试结果
Spring Boot 自定义错误

3.使用@ControllerAdvice@ExceptionHandler配置全局处理异常

编写类:

@ControllerAdvice
public class MyGlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
        Map map = new HashMap();
        map.put("code", -3);
        map.put("msg", ex.getMessage());
        return map;
    }
}

浏览器测试结果
Spring Boot 自定义错误
Postman测试结果
Spring Boot 自定义错误

4.错误信息显示优先级

@ControllerAdvice >> ErrorController >> ErrorAttribute

本文地址:https://blog.csdn.net/qq_32530561/article/details/112008557

上一篇:

下一篇: