springboot自定义404_(实用干货) | 工作中常用的Spring Boot异常处理完整示例

一:覆盖默认的异常处理

覆盖默认的异常处理有两种方式

  • BasicErrorController 方式
  • @ExceptionHandler 注解方式

在Spring boot开发中经常遇到“Whitelabel Error Page”白色标签错误页,这个页面当spring boot中发生错误时的默认处理方式,返回一个error页面,而这个页面的格式是固定的,这个页面有几个变量,映射地址:/error, status=404,type=Not Found。

SpringBoot的默认错误处理是BasicErrorController,支持两种格式:

  • 错误页面 errorHtml
  • json响应 error
5c182c68c2d86cbaf757acbbeb3f97d1.png
9258fbba2078b34b175d8743cbf37aab.png
@Controller@RequestMapping("${server.error.path:${error.path:/error}}")public class BasicErrorController extends AbstractErrorController {private final ErrorProperties errorProperties;@RequestMapping(produces = "text/html")public ModelAndView errorHtml(HttpServletRequest request,HttpServletResponse response) {HttpStatus status = getStatus(request);Map model = Collections.unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));response.setStatus(status.value());ModelAndView modelAndView = resolveErrorView(request, response, status, model);return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);}@RequestMapping@ResponseBodypublic ResponseEntity> error(HttpServletRequest request) {Map body = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.ALL));HttpStatus status = getStatus(request);return new ResponseEntity<>(body, status);}}

二:自定义错误处理BasicErrorController方式

1、 MyErrorController继承BasicErrorController

@Controllerpublic class MyErrorController extends BasicErrorController{ public MyErrorController(ServerProperties serverProperties) { super(new DefaultErrorAttributes(), serverProperties.getError());}  @Overridepublic ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); response.setStatus(status.value()); Map model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)); ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);}  @Overridepublic ResponseEntity> error(HttpServletRequest request) { HttpStatus status = getStatus(request); Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); //输出自定义的Json格式 Map map = new HashMap<>(); map.put("success", false); map.put("msg", body.get("message")); return new ResponseEntity<>(map, status); }}

2、error.html

将自定义的error.html放在src/main/resources/templates下

这里的error.html是在网上随意找的。

921a50d78d1c750ddeae9b8821c2a915.png
1af0ea458ba546b1481757d3eb8311a1.png

三:自定义错误处理 @ExceptionHandler注解方式

@ExceptionHandler的value定义的是要匹配的异常类型,这里写了一个总的异常Exception,可以针对某个具体的异常进行处理。

GlobalExceptionHandler

@ControllerAdviceclass GlobalExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "error";  // errorHtml@ExceptionHandler(value = Exception.class)public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav;}// error json@ExceptionHandler(value = NullPointerException.class)@ResponseBodypublic Map defaultJSONErrorHandler(HttpServletRequest req, Exception e) throws Exception { /* 实际使用一般返回这种格式{"success": true,"code": 200,"msg": "成功","result": {}}*/ Map res = new HashMap<>(); res.put("exception", e); res.put("url", req.getRequestURL()); return res; }}

SampleController

@Controllerpublic class SampleController { @GetMapping("/index") public ModelAndView index(Model model, HttpServletRequest request){ ModelAndView modelAndView = new ModelAndView("index"); if (1==1) { throw new IllegalArgumentException("error paramaters"); } return modelAndView; }} 
@RestControllerpublic class TestController { @GetMapping("/test") public String test(){ if (1==1) { throw new NullPointerException("null"); } return null; }}

src/main/resources/templates/error.html

 统一异常处理

Error Handler

76f6d1d5223f37633589af2d5dafdb9c.png
f5d53858791de75ba6be23591e18748c.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值