springboot實現(xiàn)全局異常處理及自定義異常類
全局異常處理及自定義異常類
全局異常處理
定義一個處理類,使用@ControllerAdvice注解。
@ControllerAdvice注解:控制器增強,一個被@Component注冊的組件。
配合@ExceptionHandler來增強所有的@requestMapping方法。
例如:@ExceptionHandler(Exception.class) 用來捕獲@requestMapping的方法中所有拋出的exception。
代碼:
@ControllerAdvice
public class GlobalDefultExceptionHandler {?? ?
?? ?//聲明要捕獲的異常
?? ?@ExceptionHandler(Exception.class)
?? ?@ResponseBody
?? ?public String defultExcepitonHandler(HttpServletRequest request,Exception e) {
?? ? ? ?return “error”;
?? ?}
}這樣,全局異常處理類完畢??梢蕴砑幼约旱倪壿?。
然后還有一個問題,有的時候,我們需要業(yè)務(wù)邏輯時拋出自定義異常,這個時候需要自定義業(yè)務(wù)異常類。
定義class:BusinessException ,使他繼承于RuntimeException.
說明:因為某些業(yè)務(wù)需要進行業(yè)務(wù)回滾。但spring的事務(wù)只針對RuntimeException的進行回滾操作。所以需要回滾就要繼承RuntimeException。
public class BusinessException extends RuntimeException{?
}然后,現(xiàn)在來稍微完善一下這個類。
當我們拋出一個業(yè)務(wù)異常,一般需要錯誤碼和錯誤信息。有助于我們來定位問題。
所以如下:
public class BusinessException extends RuntimeException{
?? ?//自定義錯誤碼
?? ?private Integer code;
?? ?//自定義構(gòu)造器,只保留一個,讓其必須輸入錯誤碼及內(nèi)容
?? ?public BusinessException(int code,String msg) {
?? ??? ?super(msg);
?? ??? ?this.code = code;
?? ?}
?
?? ?public Integer getCode() {
?? ??? ?return code;
?? ?}
?
?? ?public void setCode(Integer code) {
?? ??? ?this.code = code;
?? ?}
}這時候,我們發(fā)現(xiàn)還有一個問題,如果這樣寫,在代碼多起來以后,很難管理這些業(yè)務(wù)異常和錯誤碼之間的匹配。所以在優(yōu)化一下。
把錯誤碼及錯誤信息,組裝起來統(tǒng)一管理。
定義一個業(yè)務(wù)異常的枚舉
public enum ResultEnum {
?? ?UNKONW_ERROR(-1,"未知錯誤"),
?? ?SUCCESS(0,"成功"),
?? ?ERROR(1,"失敗"),
?? ?;?? ?
?? ?private Integer code;
?? ?private String msg;?? ?
?? ?ResultEnum(Integer code,String msg) {
?? ??? ?this.code = code;
?? ??? ?this.msg = msg;
?? ?}
?
?? ?public Integer getCode() {
?? ??? ?return code;
?? ?}
?
?? ?public String getMsg() {
?? ??? ?return msg;
?? ?}
}這個時候,業(yè)務(wù)異常類:
public class BusinessException extends RuntimeException{?? ?
?? ?private static final long serialVersionUID = 1L;?? ?
?? ?private Integer code; ?//錯誤碼?
?? ?public BusinessException() {}?? ?
?? ?public BusinessException(ResultEnum resultEnum) {
?? ??? ?super(resultEnum.getMsg());
?? ??? ?this.code = resultEnum.getCode();
?? ?}
?? ?
?? ?public Integer getCode() {
?? ??? ?return code;
?? ?}
?
?? ?public void setCode(Integer code) {
?? ??? ?this.code = code;
?? ?}
}然后再修改一下全局異常處理類:
@ControllerAdvice
public class GlobalDefultExceptionHandler {
?? ?
?? ?//聲明要捕獲的異常
?? ?@ExceptionHandler(Exception.class)
?? ?@ResponseBody
?? ?public <T> Result<?> defultExcepitonHandler(HttpServletRequest request,Exception e) {
?? ??? ?e.printStackTrace();
?? ??? ?if(e instanceof BusinessException) {
?? ??? ??? ?Log.error(this.getClass(),"業(yè)務(wù)異常:"+e.getMessage());
?? ??? ??? ?BusinessException businessException = (BusinessException)e;
?? ??? ??? ?return ResultUtil.error(businessException.getCode(), businessException.getMessage());
?? ??? ?}
?? ??? ?//未知錯誤
?? ??? ?return ResultUtil.error(-1, "系統(tǒng)異常:\\n"+e);
?? ?}?? ?
}判斷這個是否是業(yè)務(wù)異常。和系統(tǒng)異常就可以分開處理了。
全局異常處理配置
springboot Restful使用
@ControllerAdvice、@ExceptionHandler、@ResponseBody實現(xiàn)全局異常處理
@ControllerAdvice注解定義全局異常處理類@ExceptionHandler指定自定義錯誤處理方法攔截的異常類型
同一個異常被小范圍的異常類和大范圍的異常處理器同時覆蓋,會選擇小范圍的異常處理器
1.定義異常業(yè)務(wù)類
/**
* 異常VO
*
* @date 2017年2月17日
* @since 1.0.0
*/
public class ExceptionVO {
private String errorCode;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}2.定義自定義異常
package exception;
/**
* 無數(shù)據(jù)Exception
*
* @date 17/4/25
* @since 1.0.0
*/
public class NotFoundException extends SystemException {
public NotFoundException(String message) {
super(message);
}
}
/**
* 系統(tǒng)異常
*
* @date 2017年2月12日
* @since 1.0.0
*/
public class SystemException extends RuntimeException {
private static final long serialVersionUID = 1095242212086237834L;
protected Object errorCode;
protected Object[] args;
public SystemException() {
super();
}
public SystemException(String message, Throwable cause) {
super(message, cause);
}
public SystemException(String message) {
super(message);
}
public SystemException(String message, Object[] args, Throwable cause) {
super(message, cause);
this.args = args;
}
public SystemException(String message, Object[] args) {
super(message);
this.args = args;
}
public SystemException(Object errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public SystemException(Object errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public SystemException(Object errorCode, String message, Object[] args, Throwable cause) {
super(message, cause);
this.args = args;
this.errorCode = errorCode;
}
public SystemException(Object errorCode, String message, Object[] args) {
super(message);
this.args = args;
this.errorCode = errorCode;
}
public SystemException(Throwable cause) {
super(cause);
}
public Object[] getArgs() {
return args;
}
public Object getErrorCode() {
return errorCode;
}
}
3.定義全局異常處理類
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import NotFoundException;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
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.ResponseStatus;
import ExceptionVO;
/**
* WEB異常處理器
*
* @date 2017年2月16日
* @since 1.0.0
*/
@ControllerAdvice("web") //指定異常處理期攔截范圍
public class WebExceptionHandler {
static Logger LOG = LoggerFactory.getLogger(WebExceptionHandler.class);
@Autowired
private MessageSource messageSource;
@ExceptionHandler(FieldException.class)
@ResponseStatus(HttpStatus.CONFLICT) //指定http響應(yīng)狀態(tài)
@ResponseBody
/**
* 未找到數(shù)據(jù)
*
* @param e
* @return
*/
@ExceptionHandler(NotFoundException.class)//指定異常類型
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public ExceptionVO handleNotFoundException(NotFoundException e) {
ExceptionVO vo = new ExceptionVO();
fillExceptionVO(e, vo);
return vo;
}
@ExceptionHandler(SystemException.class)
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ExceptionVO handleSystemException(SystemException e) {
ExceptionVO vo = new ExceptionVO();
fillExceptionVO(e, vo);
return vo;
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public void globalError(Exception e) {
LOG.error(e.getMessage(), e);
}
/**
* 填充異常響應(yīng)消息
*
* @param e
* @param vo
*/
private void fillExceptionVO(SystemException e, ExceptionVO vo) {
if (e.getMessage() != null) {
String message = e.getMessage();
try {
message = messageSource.getMessage(e.getMessage(), e.getArgs(), LocaleContextHolder.getLocale());
} catch (NoSuchMessageException ex) {
; // ignore
}
vo.setMessage(message);
}
vo.setErrorCode(String.valueOf(e.getErrorCode()));
}
}springboot 返回 ModelAndView
package exception.handler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
@Commpent
public class OverallExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
Exception ex) {
ModelAndView mav = new ModelAndView();
System.out.println(ex.getMessage());
mav.addObject("errMsg", ex.getMessage());
mav.setViewName("error");
return mav;
}
}
其它方式:
@ControllerAdvice
public class GlobalExceptionHandler {
? ? ? @ExceptionHandler(value = Exception.class)
? ? ? public ModelAndView resolveException(HttpServletRequest request, Exception ex) throws Exception {
? ? ? ? ModelAndView mav = new ModelAndView();
? ? ? ? System.out.println(ex.getMessage());
? ? ? ? mav.addObject("errMsg", ex.getMessage());
? ? ? ? mav.setViewName("error");
? ? ? ? return mav;
? ? ? }
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
在剛開始學習Java的時候,就了解了Java基礎(chǔ)中的變量,雖然知道這個以后會經(jīng)常用到,但沒想到了基本語法這里,竟然又冒出來了成員變量和局部變量。變來變?nèi)ヌ菀鬃屓烁銜灹?,今天我們就挑揀出來梳理一下?/div> 2016-07-07
Java如何利用Easyexcel動態(tài)導(dǎo)出表頭列
這篇文章主要介紹了Java利用Easyexcel動態(tài)導(dǎo)出表頭列的實例,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
springboot動態(tài)調(diào)整日志級別的操作大全
這篇文章主要介紹了springboot動態(tài)調(diào)整日志級別的方法,本文通過實例圖文相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10最新評論

