处理方式一:实现ErrorController接口

原理:Spring Boot 将所有的错误默认映射到/error, 实现ErrorController接口

代码:

packagecom.example.demo.controller;importorg.springframework.boot.autoconfigure.web.ErrorController;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;/***Createdbylyon2017/6/17.*/@Controller@RequestMapping("error")publicclassBaseErrorControllerimplementsErrorController{@OverridepublicStringgetErrorPath(){return"error/error";}@RequestMappingpublicStringerror()throwsException{returngetErrorPath();}}


error.ftl:

<!DOCTYPEhtml><html><headlang="en"><title>SpringBootDemo-FreeMarker</title></head><body><h2>error-系统出错,请联系后台管理员</h2></body></html>


在浏览器中输入一个不存在的URL,效果如下:

---------------------------------------------分割线---------------------------------------------

处理方式二:添加自定义的错误页面

对于html静态页面:

在resources/public/error/ 下定义

如添加404页面:resources/public/error/404.html页面,中文注意页面编码


对于模板引擎页面:

在templates/error/下定义

如添加5xx页面:templates/error/5xx.ftl


注:templates/error/ 这个的优先级比较 resources/public/error/高

效果:此处输入不存在的URL,则访问我们的404.hmtl;如果抛出异常,则访问我们的5xx.ftl

---------------------------------------------分割线---------------------------------------------

处理方式三:使用注解@ControllerAdvice(全局异常处理)


ExcepitonHandler.java

packagecom.example.demo.handler;importorg.springframework.http.HttpStatus;importorg.springframework.web.bind.annotation.ControllerAdvice;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.ResponseStatus;importorg.springframework.web.servlet.ModelAndView;/***Createdbylyon2017/6/17.*/@ControllerAdvicepublicclassExcepitonHandler{/***统一异常处理**@paramexception*exception*@return*/@ExceptionHandler({RuntimeException.class})@ResponseStatus(HttpStatus.OK)publicModelAndViewprocessException(RuntimeExceptionexception){System.out.println("自定义异常处理-RuntimeException");ModelAndViewm=newModelAndView();m.addObject("roncooException",exception.getMessage());m.setViewName("error/500");returnm;}/***统一异常处理**@paramexception*exception*@return*/@ExceptionHandler({Exception.class})@ResponseStatus(HttpStatus.OK)publicModelAndViewprocessException(Exceptionexception){System.out.println("自定义异常处理-Exception");ModelAndViewm=newModelAndView();m.addObject("roncooException",exception.getMessage());m.setViewName("error/500");returnm;}}


500.ftl:

<!DOCTYPEhtml><html><headlang="en"><title>SpringBootDemo-FreeMarker</title></head><body><h2>500-系统错误</h2><h2>${roncooException}</h2></body></html>


测试:输入一个会抛异常的URL