springboot框架的全局異常處理方案詳解

系統框架搭建的前期過程中,為瞭約束代碼規范,我們會對一些通用功能做一些處理,比如聲明一些系統公用錯誤類、封裝通用返回結果、統一異常處理等,這樣做的優勢是團隊開發過程中能夠形成統一的代碼規范,增強代碼可讀性,同時又便於後期代碼維護。本文主要介紹下框架中異常的處理:

1.聲明全局異常處理類,並添加@ControllerAdvice和@RestController註解
代碼如下:

@ControllerAdvice
@RestController
public class GlobalExceptionHandler {
	
	private final Logger logger = Logger.getLogger(GlobalExceptionHandler.class);

	//空指針異常
  @ExceptionHandler(NullPointerException.class)
  public Map<String, Object> nullPointer(NullPointerException e,HttpServletRequest req){
    logger.error(e.getMessage());
		e.printStackTrace();
    return ResultObject.newResultObj(ErrorCode.NULLPOINTER);
  }
	
	//IO異常
	@ExceptionHandler(IOException.class,HttpServletRequest req, HttpServletResponse res)
  public Map<String, Object> IOException(IOException e){
  	 logger.error(e.getMessage());
		 e.printStackTrace();
     return ResultObject.newResultObj(ErrorCode.IOEXCEPTION);
  }
  
	
	//權限不足異常	
	@ExceptionHandler(UnauthorizedException.class)
	public Map<String, Object> unauth(HttpServletRequest req, HttpServletResponse res){
		return ResultObject.newResultObj(ErrorCode.UNAUTH);
	}
	
	//未登錄異常	
	@ExceptionHandler(AuthorizationException.class)
	public Map<String, Object> unlogin(HttpServletRequest req, HttpServletResponse res){
		return ResultObject.newResultObj(ErrorCode.NOTLOGIN);
	}
	
	//其它異常
	@ExceptionHandler(Exception.class)
	public Map<String, Object> error(Exception e,HttpServletRequest req, HttpServletResponse res){
		logger.error(e.getMessage());
		e.printStackTrace();
		return ResultObject.newResultObj(ErrorCode.SYSTEM);
	}
	
}

2.聲明系統通用錯誤處理類

/**
 * 系統通用錯誤處理類
 */
public class ErrorCode {

  //返回碼
  private int code = 0;
	
  //描述信息
  private String errmsg = "SUCCESS";
	
  //成功
  public static final ErrorCode SUCCESS 					  = new ErrorCode(0,"SUCCESS");
  public static final ErrorCode PARAMS 					  = new ErrorCode(100000,"參數錯誤");
  public static final ErrorCode SYSTEM 					  = new ErrorCode(100001,"系統錯誤");
	public static final ErrorCode UNLOGIN 					  = new ErrorCode(100002,"未登錄");
  public static final ErrorCode UNAUTH 					  = new ErrorCode(100003,"權限錯誤");
	public static final ErrorCode NULLPOINTER 					= new ErrorCode(100004,"空指針錯誤");
	public static final ErrorCode IOEXCEPTION 					= new ErrorCode(100005,"IO錯誤");
  public static final ErrorCode UPLOAD_FAIL 					= new ErrorCode(100006,"文件上傳失敗");
  public static final ErrorCode REPEAT 					  = new ErrorCode(100007,"數據已存在");

  public ErrorCode() {}

  @Override
  public String toString() {
    return String.format("{\"errmsg\": \"%s\", \"code\": %d}", errmsg, code);
  }

  public int getCode() {
    return code;
  }

  public ErrorCode setCode(int code) {
    this.code = code;
    return this;
  }

  public String getErrmsg() {
    return errmsg;
  }

  public ErrorCode setErrmsg(String errmsg) {
    this.errmsg = errmsg;
    return this;
  }

  public ErrorCode(int code, String errmsg) {
    this.code = code;
    this.errmsg = errmsg;
  }

}

3.聲明全局異常處理類中的結果返回類

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.xxx.ErrorCode;//此處引用自己errorCode類所在的包路徑
import org.json.JSONObject;

public class ResultObject {	
	
	/**
	 * 輸出錯誤信息
	 * @param errorCode
	 */
	public static Map<String, Object> newResultObj(ErrorCode errorCode){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("code", errorCode.getCode());
		obj.put("errmsg", errorCode.getErrmsg());
		return obj;
	}
	
	/**
	 * 輸出帶數據的成功信息
	 * @param data
	 */
	public static Map<String, Object> newResultObj(Object data){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("code", ErrorCode.SUCCESS.getCode());
		obj.put("errmsg", ErrorCode.SUCCESS.getErrmsg());
		if(null != data){
			obj.put("data", data);
		}
		return obj;		
	}
	
	/**
	 * 輸出帶數據的錯誤信息
	 * @param errorCode
	 * @param data
	 */
	public static Map<String, Object> newResultObj(ErrorCode errorCode, Object data){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("code", errorCode.getCode());
		obj.put("errmsg", errorCode.getErrmsg());
		if(null != data){
			obj.put("data", data);
		}
		return obj;				
	}
	
	
	/**
	 * 輸出結果
	 */
	public static void outputResult(HttpServletResponse response, ErrorCode errorCode){
		try {
			JSONObject json = new JSONObject();
			json.put("code", errorCode.getCode());
			json.put("errmsg", errorCode.getErrmsg());
			
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(json.toString());
		} catch (Exception e1) {
		}
	}
}

到此這篇關於springboot框架的全局異常處理方案的文章就介紹到這瞭,更多相關springboot全局異常處理內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: