SpringBoot優(yōu)雅捕捉異常的兩種方法小結(jié)
一、前言
SpringBoot框架對(duì)異常的處理提供了幾種很強(qiáng)大的方法,我們可以通過@ControllerAdvice和@ExceptionHandler注解實(shí)現(xiàn)全局異常的處理,也可以通過實(shí)現(xiàn)HandlerExceptionResolve接口來完成全局異常的處理。
二、全局異常處理方式一
通過@ControllerAdvice和@ExceptionHandler注解實(shí)現(xiàn)全局異常攔截,它可以攔截controller層請(qǐng)求方法拋出的異常信息,同時(shí)外加@ ResponseBody注解,可以實(shí)現(xiàn)響應(yīng)類型為json格式?;蛘咧苯邮褂聾RestControllerAdvice和@ExceptionHandler注解的方式實(shí)現(xiàn)響應(yīng)類型為json格式的數(shù)據(jù)。
1.添加依賴
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>2.自定義異常類
package com.example.dataproject.exception;
/**
* @author qx
* @date 2024/8/8
* @des 自定義異常
*/
public class ServiceException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public ServiceException(String message, Integer code) {
super(message);
this.code = code;
}
}3.全局異常處理類
包含對(duì)自定義異常和空指針異常的處理。
package com.example.dataproject.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2024/8/8
* @des 全局異常處理類
*/
@RestControllerAdvice
@Slf4j
public class GlobalException {
@ExceptionHandler(value = {Exception.class})
public Map<String, Object> exceptionHandler(HttpServletRequest request, Exception e) {
log.info("未知異常,請(qǐng)求地址:{},錯(cuò)誤信息:{}", request.getRequestURI(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", 999);
map.put("message", e.getMessage());
return map;
}
@ExceptionHandler(value = {ServiceException.class})
public Map<String, Object> serviceExceptionHandler(HttpServletRequest request, ServiceException e) {
log.info("自定義異常,請(qǐng)求地址:{},錯(cuò)誤信息:{}", request.getRequestURI(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("message", e.getMessage());
return map;
}
@ExceptionHandler(value = {NullPointerException.class})
public Map<String, Object> nullPointExceptionHandler(HttpServletRequest request, NullPointerException e) {
log.info("空指針異常,請(qǐng)求地址:{},錯(cuò)誤信息:{}", request.getRequestURI(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", 500);
map.put("message", e.getMessage());
return map;
}
}4.創(chuàng)建控制層測(cè)試
package com.example.dataproject.controller;
import com.example.dataproject.exception.ServiceException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author qx
* @date 2024/8/8
* @des 測(cè)試
*/
@RestController
public class IndexController {
@GetMapping("/null")
public String testNull() {
String s = null;
//拋出空指針異常 全局異常中的空指針異常處理會(huì)捕獲到這個(gè)異常
if (true) {
throw new NullPointerException("空指針異常");
}
return "null success";
}
@GetMapping("/service")
public String testService() {
if (true) {
//拋出自定義異常 全局異常中的自定義異常處理會(huì)捕獲到這個(gè)異常
throw new ServiceException("自定義服務(wù)異常", 888);
}
return "service success";
}
@GetMapping("/exception")
public String testException() {
if (true) {
throw new RuntimeException("其他異常");
}
return "exception success";
}
}5.啟動(dòng)程序并訪問請(qǐng)求進(jìn)行測(cè)試
測(cè)試空指針異常

測(cè)試自定義服務(wù)異常

其他異常

6.404異常特殊處理
默認(rèn)情況下,@ExceptionHandler注解無法捕捉到 404 異常,比如請(qǐng)求一個(gè)無效的地址,返回信息如下:

如果想要捕捉到這種異常,可以在application.properties文件中添加如下配置來實(shí)現(xiàn)。
# 如果沒有找到請(qǐng)求地址,拋異常 spring.mvc.throw-exception-if-no-handler-found=true # 關(guān)閉默認(rèn)的靜態(tài)資源路徑映射 spring.web.resources.add-mappings=false
啟動(dòng)服務(wù),再次發(fā)起地址請(qǐng)求,結(jié)果如下:

7.自定義異常頁面的實(shí)現(xiàn)
某些場(chǎng)景下,當(dāng)發(fā)生異常時(shí)希望跳轉(zhuǎn)到自定義的異常頁面,如何實(shí)現(xiàn)呢?
首先,這里基于thymeleaf模板引擎來開發(fā)頁面,在templates目錄下創(chuàng)建一個(gè)異常頁面error.html。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>錯(cuò)誤</title>
</head>
<body>
出錯(cuò)啦,請(qǐng)與管理員聯(lián)系<br>
錯(cuò)誤詳情:<span th:text="${message}"></span>
</body>
</html>我們重新修改一下全局異常處理類,讓異常返回結(jié)果到頁面中。
package com.example.dataproject.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2024/8/8
* @des 全局異常處理類
*/
@ControllerAdvice
@Slf4j
public class GlobalException {
@ExceptionHandler(value = {Exception.class})
public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) {
log.info("未知異常,請(qǐng)求地址:{},錯(cuò)誤信息:{}", request.getRequestURI(), e.getMessage());
/* Map<String, Object> map = new HashMap<>();
map.put("code", 999);
map.put("message", e.getMessage());
return map;*/
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error");
modelAndView.addObject("message", e.getMessage());
return modelAndView;
}
@ExceptionHandler(value = {ServiceException.class})
@ResponseBody
public Map<String, Object> serviceExceptionHandler(HttpServletRequest request, ServiceException e) {
log.info("自定義異常,請(qǐng)求地址:{},錯(cuò)誤信息:{}", request.getRequestURI(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", e.getCode());
map.put("message", e.getMessage());
return map;
}
@ExceptionHandler(value = {NullPointerException.class})
@ResponseBody
public Map<String, Object> nullPointExceptionHandler(HttpServletRequest request, NullPointerException e) {
log.info("空指針異常,請(qǐng)求地址:{},錯(cuò)誤信息:{}", request.getRequestURI(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", 500);
map.put("message", e.getMessage());
return map;
}
}我們重新請(qǐng)求剛才不存在的訪問時(shí),這個(gè)時(shí)候跳轉(zhuǎn)到了頁面,并在頁面中顯示了異常的信息。

三、全局異常處理方式二
在 Spring Boot 中,除了通過@ControllerAdvice和@ExceptionHandler注解實(shí)現(xiàn)全局異常處理外,還有一種通過實(shí)現(xiàn)HandlerExceptionResolver接口來完成全局異常的處理。
具體實(shí)現(xiàn)示例如下:
package com.example.dataproject.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author qx
* @date 2024/8/8
* @des 全局異常處理
*/
@Component
@Slf4j
public class GlobalExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
log.error("接口請(qǐng)求出現(xiàn)異常,請(qǐng)求地址:{},錯(cuò)誤信息:{}", request.getRequestURI(), e.getMessage());
if (e instanceof NullPointerException) {
// 設(shè)置響應(yīng)類型為json格式
ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
mv.addObject("code", 500);
mv.addObject("msg", e.getMessage());
return mv;
} else {
// 設(shè)置響應(yīng)類型為錯(cuò)誤頁面
ModelAndView mv = new ModelAndView();
mv.addObject("message", e.getMessage());
mv.setViewName("error");
return mv;
}
}
}如果是空指針異常的話會(huì)返回json數(shù)據(jù)格式,如果是其他異常會(huì)在頁面上顯示異常的信息。
其他異常

空指針異常

雖然這種方式能夠處理全局異常,但是 Spring 官方不推薦使用它;同時(shí)實(shí)測(cè)過程中發(fā)現(xiàn)它無法攔截 404 錯(cuò)誤,當(dāng)請(qǐng)求錯(cuò)誤地址時(shí),會(huì)優(yōu)先被DefaultHandlerExceptionResolver默認(rèn)異常處理類攔截,自定義的異常處理類無法捕捉。
到此這篇關(guān)于SpringBoot優(yōu)雅捕捉異常的兩種方法小結(jié)的文章就介紹到這了,更多相關(guān)SpringBoot 捕捉異常內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解在SpringBoot應(yīng)用中獲取應(yīng)用上下文方法
本篇文章主要介紹了詳解在SpringBoot應(yīng)用中獲取應(yīng)用上下文方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-04-04
SpringBoot+WebMagic+MyBaties實(shí)現(xiàn)爬蟲和數(shù)據(jù)入庫的示例
WebMagic是一個(gè)開源爬蟲框架,本項(xiàng)目通過在SpringBoot項(xiàng)目中使用WebMagic去抓取數(shù)據(jù),最后使用MyBatis將數(shù)據(jù)入庫。具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10
SpringBoot修改子模塊Module的jdk版本的方法 附修改原因
這篇文章主要介紹了SpringBoot修改子模塊Module的jdk版本的方法 附修改原因,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Spring Boot集成kubernetes客戶端實(shí)現(xiàn)API操作k8s集群的方案
Kubernetes是一個(gè)開源的容器編排平臺(tái),可以自動(dòng)化在部署、管理和擴(kuò)展容器化應(yīng)用過程中涉及的許多手動(dòng)操作,這篇文章主要介紹了Spring Boot集成kubernetes客戶端實(shí)現(xiàn)API操作k8s集群,需要的朋友可以參考下2024-08-08
Java使用Tess4J實(shí)現(xiàn)圖像識(shí)別方式
這篇文章主要介紹了Java使用Tess4J實(shí)現(xiàn)圖像識(shí)別方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
Java 文創(chuàng)商城系統(tǒng)的實(shí)現(xiàn)流程
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+mysql+maven+tomcat實(shí)現(xiàn)一個(gè)文創(chuàng)商城系統(tǒng),大家可以在過程中查缺補(bǔ)漏,提升水平2021-11-11
SpringBoot整合Mybatis使用Druid數(shù)據(jù)庫連接池
這篇文章主要介紹了SpringBoot整合Mybatis使用Druid數(shù)據(jù)庫連接池,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03

