新建exception目錄,用來進(jìn)行自定義的全局異常處理。
(1)新建自定義的GlobalException基 類繼承RuntimeException類,我們自定義的異常類全部需要繼承GlobalException基類進(jìn)行處理。
這里我們直接利用之前定義的錯(cuò)誤碼接口類。
/**
* 自定義的全局異常
*/
public class GlobalException extends RuntimeException{
private IErrorCode errorCode;
public GlobalException(String message) {
super(message);
}
public GlobalException(Throwable cause) {
super(cause);
}
public GlobalException(String message, Throwable cause) {
super(message, cause);
}
public IErrorCode getErrorCode() {
return errorCode;
}
}
(2)在exception目錄下,新建GlobalExceptionHandler類,攔截異常類。文章來源:http://www.zghlxwxcb.cn/news/detail-669970.html
在此類中可以捕獲并將異常類轉(zhuǎn)換為可接受的信息返回給前端,防止將異常直接拋出到前端。文章來源地址http://www.zghlxwxcb.cn/news/detail-669970.html
/**
* 捕獲并處理全局異常
*/
@ResponseBody
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 捕獲并處理所有自定義異常
*/
@ExceptionHandler(value = GlobalException.class)
public HttpResult handle(GlobalException e) {
if (e.getErrorCode() != null) {
return HttpResult.fail(e.getErrorCode());
}
return HttpResult.fail(e.getMessage());
}
/**
* 捕獲并處理方法參數(shù)未驗(yàn)證異常
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public HttpResult handleValidException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
String message = null;
if (bindingResult.hasErrors()) {
FieldError fieldError = bindingResult.getFieldError();
if (fieldError != null) {
message = fieldError.getField()+fieldError.getDefaultMessage();
}
}
return HttpResult.validateFailed(message);
}
/**
* 捕獲并處理綁定異常
*/
@ExceptionHandler(value = BindException.class)
public HttpResult handleValidException(BindException e) {
BindingResult bindingResult = e.getBindingResult();
String message = null;
if (bindingResult.hasErrors()) {
FieldError fieldError = bindingResult.getFieldError();
if (fieldError != null) {
message = fieldError.getField()+fieldError.getDefaultMessage();
}
}
return HttpResult.validateFailed(message);
}
}
到了這里,關(guān)于后端項(xiàng)目開發(fā):整合全局異常處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!