JAVA異常處理,SpringBoot的Web開發入門案例3—異常處理

 2023-11-05 阅读 27 评论 0

摘要:SpringBoot的Web開發入門案例3—異常處理 SpringBoot 默認404界面(由org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration類提供): SpringBoot 默認500界面(由org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfig

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注解定義全局異常

  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)@ResponseBodypublic 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
    在這里插入圖片描述

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/168548.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息