Java秒殺實戰-2-5異常處理

1.實現思路

 1.1 創建 GlobleExceptionHandler  ,用註解@ControllerAdvice,@ResponseBody 修飾,

@ExceptionHandler(value=Exception.class) 定義處理哪種異常,傳入參數HttpServletRequest request ,Exception e ,判斷傳入的異常類型instacneof GlobalException ,如果是綁定異常BindExcpetion獲取getAllErrors 返回CodeMsg.BIND_ERROR,如果是其他異常返回服務端異常。
package com.zengjx.miaosha.exception;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.zengjx.miaosha.result.CodeMsg;
import com.zengjx.miaosha.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
	@ExceptionHandler(value=Exception.class)
	public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
		e.printStackTrace();
		if(e instanceof GlobalException) {
			GlobalException ex = (GlobalException)e;
			return Result.error(ex.getCm());
		}else if(e instanceof BindException) {
			BindException ex = (BindException)e;
			List<ObjectError> errors = ex.getAllErrors();
			ObjectError error = errors.get(0);
			String msg = error.getDefaultMessage();
			return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
		}else {
			return Result.error(CodeMsg.SERVER_ERROR);
		}
	}
}

1.2. 定義全局異常類GlobalException 繼承與RuntimeException  

package com.zengjx.miaosha.exception;

import com.zengjx.miaosha.result.CodeMsg;

public class GlobalException extends RuntimeException{

	private static final long serialVersionUID = 1L;
	
	private CodeMsg cm;
	
	public GlobalException(CodeMsg cm) {
		super(cm.toString());
		this.cm = cm;
	}

	public CodeMsg getCm() {
		return cm;
	}

}

 

 

發佈了247 篇原創文章 · 獲贊 11 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章