這篇文章主要介紹“SpringBoot全局異常問(wèn)題怎么解決”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“SpringBoot全局異常問(wèn)題怎么解決”文章能幫助大家解決問(wèn)題。

枝江ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書(shū)未來(lái)市場(chǎng)廣闊!成為成都創(chuàng)新互聯(lián)的ssl證書(shū)銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18982081108(備注:SSL證書(shū)合作)期待與您的合作!
SpringBoot 是為了簡(jiǎn)化 Spring 應(yīng)用的創(chuàng)建、運(yùn)行、調(diào)試、部署等一系列問(wèn)題而誕生的產(chǎn)物,自動(dòng)裝配的特性讓我們可以更好的關(guān)注業(yè)務(wù)本身而不是外部的XML配置,我們只需遵循規(guī)范,引入相關(guān)的依賴就可以輕易的搭建出一個(gè) WEB 工程
實(shí)際項(xiàng)目開(kāi)發(fā)中,程序往往會(huì)發(fā)生各式各樣的異常情況,特別是身為服務(wù)端開(kāi)發(fā)人員的我們,總是不停的編寫接口提供給前端調(diào)用,分工協(xié)作的情況下,避免不了異常的發(fā)生,如果直接將錯(cuò)誤的信息直接暴露給用戶,這樣的體驗(yàn)可想而知,且對(duì)黑客而言,詳細(xì)異常信息往往會(huì)提供非常大的幫助…
采用try-catch的方式,手動(dòng)捕獲異常信息,然后返回對(duì)應(yīng)的結(jié)果集,相信很多人都看到過(guò)類似的代碼(如:封裝成Result對(duì)象);該方法雖然間接性的解決錯(cuò)誤暴露的問(wèn)題,同樣的弊端也很明顯,增加了大量的代碼量,當(dāng)異常過(guò)多的情況下對(duì)應(yīng)的catch層愈發(fā)的多了起來(lái),很難管理這些業(yè)務(wù)異常和錯(cuò)誤碼之間的匹配,所以最好的方法就是通過(guò)簡(jiǎn)單配置全局掌控….
接下來(lái)就看看 Spring Boot 提供的解決方案
在 pom.xml 中添加上 spring-boot-starter-web 的依賴即可
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
自定義異常
在應(yīng)用開(kāi)發(fā)過(guò)程中,除系統(tǒng)自身的異常外,不同業(yè)務(wù)場(chǎng)景中用到的異常也不一樣,為了與標(biāo)題 輕松搞定全局異常 更加的貼切,定義個(gè)自己的異常,看看如何捕獲…
package com.battcn.exception;
/**
* 自定義異常
*
* @author Levin
* @since
public class CustomException extends RuntimeException
private static final long serialVersionUID = 4564124491192825748L;
private int code;
public CustomException() {
super();
}
public CustomException(int code, String message) {
super(message);
this.setCode(code);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}定義返回的異常信息的格式,這樣異常信息風(fēng)格更為統(tǒng)一
package com.battcn.exception; /** * @author Levin * @since public class ErrorResponseEntity private int code; private String message; // 省略 get set
仔細(xì)一看是不是和平時(shí)正常寫的代碼沒(méi)啥區(qū)別,不要急,接著看….
package com.battcn.controller;
import com.battcn.exception.CustomException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* 全局異常演示
*
* @author Levin
* @since
@RestController
public class ExceptionController
@GetMapping("/test3")
public String test3(Integer num) {
// TODO 演示需要,實(shí)際上參數(shù)是否為空通過(guò) @RequestParam(required = true) 就可以控制
if (num == null) {
throw new CustomException(400, "num不能為空");
}
int i = 10 / num;
return "result:"注解概述:
@ControllerAdvice捕獲 Controller 層拋出的異常,如果添加 @ResponseBody 返回信息則為JSON 格式。
@RestControllerAdvice相當(dāng)于 @ControllerAdvice 與 @ResponseBody 的結(jié)合體。
@ExceptionHandler統(tǒng)一處理一種類的異常,減少代碼重復(fù)率,降低復(fù)雜度。
創(chuàng)建一個(gè) GlobalExceptionHandler 類,并添加上 @RestControllerAdvice 注解就可以定義出異常通知類了,然后在定義的方法中添加上 @ExceptionHandler 即可實(shí)現(xiàn)異常的捕捉…
package com.battcn.config;
import com.battcn.exception.CustomException;
import com.battcn.exception.ErrorResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 全局異常處理
*
* @author Levin
* @since
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler
/**
* 定義要捕獲的異常 可以多個(gè) @ExceptionHandler({})
*
* @param request request
* @param e exception
* @param response response
* @return
@ExceptionHandler(CustomException.class)
public ErrorResponseEntity customExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
CustomException exception = (CustomException) e;
return new ErrorResponseEntity(exception.getCode(), exception.getMessage());
}
/**
* 捕獲 RuntimeException 異常
* TODO 如果你覺(jué)得在一個(gè) exceptionHandler 通過(guò) if (e instanceof xxxException) 太麻煩
* TODO 那么你還可以自己寫多個(gè)不同的 exceptionHandler 處理不同異常
*
* @param request request
* @param e exception
* @param response response
* @return
@ExceptionHandler(RuntimeException.class)
public ErrorResponseEntity runtimeExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
RuntimeException exception = (RuntimeException) e;
return new ErrorResponseEntity(400, exception.getMessage());
}
/**
* 通用的接口映射異常處理方
*/
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
HttpStatus status, WebRequest request) {
if (ex instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
}
if (ex instanceof MethodArgumentTypeMismatchException) {
MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
logger.error("參數(shù)轉(zhuǎn)換失敗,方法:" + exception.getParameter().getMethod().getName() + ",參數(shù):" + exception.getName()
+ ",信息:" + exception.getLocalizedMessage());
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "參數(shù)轉(zhuǎn)換失敗"), status);
}
return new ResponseEntity<>(new ErrorResponseEntity(status.value(), "參數(shù)轉(zhuǎn)換失敗"), status);
}
}完成準(zhǔn)備事項(xiàng)后,啟動(dòng)Chapter17Application,通過(guò)下面的測(cè)試結(jié)果可以發(fā)現(xiàn),真的是 so easy,代碼變得整潔了,擴(kuò)展性也變好了…
訪問(wèn) http://localhost:8080/test3
{"code":400,"message":"num不能為空"}訪問(wèn) http://localhost:8080/test3?num=0
{"code":400,"message":"/ by zero"}訪問(wèn) http://localhost:8080/test3?num=5
result:2
關(guān)于“SpringBoot全局異常問(wèn)題怎么解決”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。
網(wǎng)頁(yè)名稱:SpringBoot全局異常問(wèn)題怎么解決
轉(zhuǎn)載源于:http://chinadenli.net/article4/pgjhie.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、外貿(mào)建站、網(wǎng)站營(yíng)銷、搜索引擎優(yōu)化、網(wǎng)頁(yè)設(shè)計(jì)公司、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)