SpringBoot的Web开发入门案例3—异常处理
SpringBoot 默认404界面(由org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration类提供):
SpringBoot 默认500界面(由org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration类提供):
1. 定制自己的异常页面
在 resources/templates 目录下新建error文件夹,在此文件夹下新建4xx.html、404.html、500.html
4xx.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>error:4xx</h1>
</body>
</html>
404.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>error:404</h1>
</body>
</html>
500.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>error:500</h1>
</body>
</html>
当出现404错误时将显示自定义的404页面:
而在Postman中显示的却是json数据:
当出现以4开头的非404错误时显示自定义的4xx页面:
当出现500错误时将显示自定义的500页面:
2. 使用@ControllerAdvice注解定义全局异常
- 创建 GlobalExceptionHandler 类(用 @ControllerAdvice 标注该类,用 @ExceptionHandler 标注方法,指定处理的异常类型。)
package com.blu.util;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/*
* 异常处理(自定义json响应)
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value=Exception.class)
@ResponseBody
public Map<String,Object> globalErrorHandler(){
Map<String,Object> map = new HashMap<>();
map.put("errorMsg", "失败了");
map.put("code", "404");
return map;
}
}
- 在DemoController中添加exceTest方法
@GetMapping("/exce/{id}")
public String exceTest(@PathVariable("id")Integer id) {
if(id==0) {
throw new RuntimeException("id不能为0");
}
return "login";
}
- 浏览器访问http://localhost:8088/exce/0,显示json数据。
- 浏览器访问http://localhost:8088/exce/1,显示login页面
- Postman访问http://localhost:8088/exce/0,显示的也是json数据
- Postman访问http://localhost:8088/exce/1,显示的是html