SpringBoot的Web开发入门案例3—异常处理

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注解定义全局异常

  1. 创建 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;
	}
}
  1. 在DemoController中添加exceTest方法
	@GetMapping("/exce/{id}")
	public String exceTest(@PathVariable("id")Integer id) {
		if(id==0) {
			throw new RuntimeException("id不能为0");
		}
		return "login";
	}
  1. 浏览器访问http://localhost:8088/exce/0,显示json数据。
    在这里插入图片描述
  2. 浏览器访问http://localhost:8088/exce/1,显示login页面
    在这里插入图片描述
  3. Postman访问http://localhost:8088/exce/0,显示的也是json数据
    在这里插入图片描述
  4. Postman访问http://localhost:8088/exce/1,显示的是html
    在这里插入图片描述
发布了20 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/BLU_111/article/details/105572999