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

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

(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
[quote]server.error.whitelabel.enabled=false # Enable the default error page displayed in browsers in case of a server error.[/quote]

(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";
}


[quote]src/main/resources/templates/error/404.html
src/main/resources/templates/error/500.html[/quote]

(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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值