這里解決之前留下來(lái)的問(wèn)題,當(dāng)程序沒(méi)有正常返回時(shí)候
就是程序由于運(yùn)行時(shí)異常導(dǎo)致的結(jié)果,有些異常我們可,能無(wú)法提前預(yù)知,不能正常走到我們r(jià)eturn的R對(duì)象返回。這個(gè)時(shí)候該如何處理
在SpringBoot中,可以使用@ControllerAdvice
注解來(lái)啟用全局異常處理。通過(guò)使用@ControllerAdvice注解,可以捕獲應(yīng)用程序中的所有異常,從而實(shí)現(xiàn)統(tǒng)一的異常處理。如果要自定義異常處理方法,可以使用@ExceptionHandler
注解,并指定要捕獲的異常類型。這樣就可以對(duì)指定的異常進(jìn)行統(tǒng)一的處理。因此,通過(guò)@ControllerAdvice和@ExceptionHandler注解的組合,可以實(shí)現(xiàn)全局的異常處理。
代碼示列
package cn.soboys.springbootrestfulapi.common.exception;
import cn.soboys.springbootrestfulapi.common.resp.R;
import cn.soboys.springbootrestfulapi.common.resp.ResultCodeEnum;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;
/**
* @author 公眾號(hào) 程序員三時(shí)
* @version 1.0
* @date 2023/4/29 00:21
* @webSite https://github.com/coder-amiao
* 統(tǒng)一異常處理器
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 通用異常處理方法
**/
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e) {
e.printStackTrace();
return R.setResult(ResultCodeEnum.INTERNAL_SERVER_ERROR);
}
/**
* 指定異常處理方法
**/
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public R error(NullPointerException e) {
e.printStackTrace();
return R.setResult(ResultCodeEnum.NULL_POINT);
}
/**
* 處理Get請(qǐng)求中 使用@Valid 驗(yàn)證路徑中請(qǐng)求實(shí)體校驗(yàn)失敗后拋出的異常
*/
@ExceptionHandler(BindException.class)
@ResponseBody
public R BindExceptionHandler(BindException e) {
String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
return R.failure().code(ResultCodeEnum.PARAM_ERROR.getCode()).message(message);
}
/**
* 處理Get請(qǐng)求中 使用@Validated 驗(yàn)證路徑中 單個(gè)參數(shù)請(qǐng)求失敗拋出異常
* @param e
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
public R ConstraintViolationExceptionHandler(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
return R.failure().code(ResultCodeEnum.PARAM_ERROR.getCode()).message(message);
}
/**
* 自定義異常處理方法
*
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseBody
public R error(BusinessException e) {
e.printStackTrace();
return R.failure().message(e.getMessage()).code(e.getCode());
}
}
異常處理,能夠減少代碼的重復(fù)度和復(fù)雜度,有利于代碼的維護(hù),并且能夠快速定位到BUG,大大提高我們的開發(fā)效率。
通過(guò)@ControllerAdvice
返回對(duì)應(yīng)錯(cuò)誤視圖頁(yè)面,@RestControllerAdvice
返回json 格式的錯(cuò)誤api,也可以通過(guò)@ControllerAdvice
在方法上加上@ResponseBody
返回對(duì)應(yīng)json格式, 類比,controller中返回是一樣的
這樣暫時(shí)解決了,我們上一片文章留下問(wèn)題
思考
其實(shí)這樣寫,還是不夠完美,我們知道我們錯(cuò)誤類型有很多種,參數(shù)錯(cuò)誤也有很多,參數(shù)校驗(yàn)還沒(méi)有達(dá)到框架級(jí)別,
例如這個(gè)是阿里云ECS錯(cuò)誤
{
"RequestId": "5E571499-13C5-55E3-9EA6-DEFA0DBC85E4",
"HostId": "ecs-cn-hangzhou.aliyuncs.com",
"Code": "InvalidOperation.NotSupportedEndpoint",
"Message": "The specified endpoint can't operate this region. Please use API DescribeRegions to get the appropriate endpoint, or upgrade your SDK to latest version.",
"Recommend": "https://next.api.aliyun.com/troubleshoot?q=InvalidOperation.NotSupportedEndpoint&product=Ecs"
}
這是新浪api的
{
"request": "/statuses/home_timeline.json",
"error_code": "20502",
"error": "Need you follow uid."
}
或者說(shuō)這樣
{
"result": false,
"error": {"code": 102, "message": "Validation failed: Wrong NAME."}
}
我們?nèi)绾卧谶M(jìn)一步改進(jìn)呢,
下一篇文章會(huì)繼續(xù)分享,留下你的思考文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-433240.html
準(zhǔn)備從零做一套自己的開發(fā)腳手架模板 ,關(guān)注公眾 程序員三時(shí)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-433240.html
到了這里,關(guān)于SpringBoot定義優(yōu)雅全局統(tǒng)一Restful API 響應(yīng)框架二的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!