我們一起聊聊 Spring 統(tǒng)一處理異常與響應(yīng)
作者:了不起
定義統(tǒng)一的異常處理流程,通過@RestControllerAdvice與@ExceptionHandler注解可以對(duì)Controller中的異常統(tǒng)一處理。
在web開發(fā)中,規(guī)范所有請(qǐng)求響應(yīng)類型,不管是對(duì)前端數(shù)據(jù)處理,還是后端統(tǒng)一數(shù)據(jù)解析都是非常重要的。今天我們簡單的方式實(shí)現(xiàn)如何實(shí)現(xiàn)這一效果。
實(shí)現(xiàn)方式
- 定義響應(yīng)類型
public class ResponseResult<T> {
private static final String SUCCESS_CODE = "000";
private static final String FAILURE_CODE = "999";
private String code;
private String message;
private T data;
public static <T> ResponseResult<T> ok(T data){
ResponseResult responseResult = new ResponseResult();
responseResult.setCode(SUCCESS_CODE);
responseResult.setData(data);
return responseResult;
}
public static ResponseResult fail(String code, String message){
if( code == null ){
code = FAILURE_CODE;
}
ResponseResult responseResult = new ResponseResult();
responseResult.setCode(code);
responseResult.setMessage(message);
return responseResult;
}
public static ResponseResult fail(String message){
return fail(FAILURE_CODE, message);
}
}
- 定義統(tǒng)一的異常處理流程,通過@RestControllerAdvice與@ExceptionHandler注解可以對(duì)Controller中的異常統(tǒng)一處理。
@RestControllerAdvice
public class ControllerAdviceHandle {
@ExceptionHandler(Exception.class)
public ResponseResult handleException(Exception exception) {
BusException busException;
if (exception instanceof BusException asException) {
busException = asException;
} else {
busException = convertException(exception);
}
return ResponseResult.fail(busException.getCode(), busException.getMessage());
}
}
- 定義統(tǒng)一響應(yīng)攔截,通過是實(shí)現(xiàn)接口ResponseBodyAdvice,這里可以和上面的異常一起處理。
public class ControllerAdviceHandle implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,
ServerHttpRequest request, ServerHttpResponse response) {
if( body instanceof ResponseResult){
return body;
}
return ResponseResult.ok(body);
}
}
- 定義spring配置,實(shí)現(xiàn)自動(dòng)裝配
在resource目錄添加自動(dòng)注入配置META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports,這樣通過引入jar就可以自動(dòng)使用該配置。
cn.cycad.web.response.ResponseConfig
應(yīng)用示例
- 比如現(xiàn)在有一個(gè)User實(shí)體,我們通過繼承基類。
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/{val}")
public Object get(@PathVariable("val") String val) throws BusException {
if( "1".equals(val) ){
throw new BusException("參數(shù)錯(cuò)誤");
}
return Map.of("val",val);
}
}
- 通過調(diào)用請(qǐng)求,可以看到不管是否異常,結(jié)果都是下面的格式。
{
"code": "999",
"message": null,
"data": null
}
責(zé)任編輯:武曉燕
來源:
Java技術(shù)指北