Spring Boot 入门 - 基础篇(13)- 异常处理

先要了解Spring的异常处理: http://rensanning.iteye.com/blog/2355214

(1)Spring Boot默认开启异常应答
-浏览器访问(Accept: text/html),返回“Whitelabel Error Page”错误页面
-浏览器以外访问返回JSON串:
{"timestamp":1487060396727,"status":404,"error":"Not Found","message":"No message available","path":"/test"}

(2)自定义错误页面
Thymeleaf: /src/main/resources/templates/error.html
FreeMarker: /src/main/resources/templates/error.ftl

(3)显示tomcat默认错误界面
application.properties
引用
server.error.whitelabel.enabled=false # Enable the default error page displayed in browsers in case of a server error.


(4)自定义404/500页面
@Component
public class Customizer implements EmbeddedServletContainerCustomizer {
 
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
        container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"));
    }
 
}


@RequestMapping("/404")
@ResponseStatus(HttpStatus.NOT_FOUND)
public String notFoundError() {
    return "error/404";
}

@RequestMapping("/500")
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String interdError() {
    return "error/500";
} 


引用
src/main/resources/templates/error/404.html
src/main/resources/templates/error/500.html


(5)兼容页面和API
org.springframework.boot.autoconfigure.web.ErrorController

@Controller
public class GlobalErrorController implements ErrorController {

  @Value("${server.error.path:${error.path:/error}}")
  private String errorPath;

  @Autowired
  private ErrorAttributes errorAttributes;

  @Override
  public String getErrorPath() {
    return errorPath;
  }

  @RequestMapping(value = "${server.error.path:${error.path:/error}}")
  public String error(HttpServletRequest req) {
    if (isAPIreq(req)) {
      return "forward:/api/error";
    } else {
      return "forward:/admin/error";
    }
  }

  @RequestMapping(value = "/api/error")
  @ResponseBody
  public ErrorResponse error(HttpServletRequest request) {
    // ...
    return ErrorResponse.build();
  }

  @RequestMapping("/admin/error")
  public String error(HttpServletRequest request, Model model) {
    // ...
    return "screen/error";
  }

}


src/main/resources/templates/screen/error.html

猜你喜欢

转载自rensanning.iteye.com/blog/2357382