springboot框架的全局异常处理方案详解

系统框架搭建的前期过程中,为了约束代码规范,我们会对一些通用功能做一些处理,比如声明一些系统公用错误类、封装通用返回结果、统一异常处理等,这样做的优势是团队开发过程中能够形成统一的代码规范,增强代码可读性,同时又便于后期代码维护。本文主要介绍下框架中异常的处理:

1.声明全局异常处理类,并添加@ControllerAdvice和@RestController注解
代码如下:

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

	//空指针异常
  @ExceptionHandler(NullPointerException.class)
  public Map 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 IOException(IOException e){
  	 logger.error(e.getMessage());
		 e.printStackTrace();
     return ResultObject.newResultObj(ErrorCode.IOEXCEPTION);
  }
  
	
	//权限不足异常	
	@ExceptionHandler(UnauthorizedException.class)
	public Map unauth(HttpServletRequest req, HttpServletResponse res){
		return ResultObject.newResultObj(ErrorCode.UNAUTH);
	}
	
	//未登录异常	
	@ExceptionHandler(AuthorizationException.class)
	public Map unlogin(HttpServletRequest req, HttpServletResponse res){
		return ResultObject.newResultObj(ErrorCode.NOTLOGIN);
	}
	
	//其它异常
	@ExceptionHandler(Exception.class)
	public Map 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 newResultObj(ErrorCode errorCode){
		Map obj = new HashMap();
		obj.put("code", errorCode.getCode());
		obj.put("errmsg", errorCode.getErrmsg());
		return obj;
	}
	
	/**
	 * 输出带数据的成功信息
	 * @param data
	 */
	public static Map newResultObj(Object data){
		Map obj = new HashMap();
		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 newResultObj(ErrorCode errorCode, Object data){
		Map obj = new HashMap();
		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全局异常处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(springboot框架的全局异常处理方案详解)