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>
JAVA異常處理。當出現404錯誤時將顯示自定義的404頁面:
而在Postman中顯示的卻是json數據:
當出現以4開頭的非404錯誤時顯示自定義的4xx頁面:
當出現500錯誤時將顯示自定義的500頁面:
2. 使用@ControllerAdvice注解定義全局異常
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)@ResponseBodypublic Map<String,Object> globalErrorHandler(){Map<String,Object> map = new HashMap<>();map.put("errorMsg", "失敗了");map.put("code", "404");return map;}
}
@GetMapping("/exce/{id}")public String exceTest(@PathVariable("id")Integer id) {if(id==0) {throw new RuntimeException("id不能為0");}return "login";}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态