公共异常处理

一、介绍

在解决controller层抛出的异常时,为了使我们的代码更容易维护,创建一个类集中处理异常,通过实现 @ControllerAdvice注解捕获,配合 @ExceptionHandler来增强所有的@RequestMapping方法。
@ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度
该注解作用对象为方法,并且在运行时有效,value()可以指定异常类。异常参数:包括一般的异常或特定的异常(即自定义异常),如果注解没有指定异常类,会默认进行映射。
@ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开

二、具体实现

例如:@ExceptionHandler(Exception.class) 用来捕获@requestMapping的方法中所有抛出的exception。

/**  * 统一异常处理类  */ 
@ControllerAdvice 
public class BaseExceptionHandler {          	
		@ExceptionHandler(value = Exception.class)     	
		@ResponseBody     
		public Result error( Exception e) {         	
				e.printStackTrace();                 
				return new Result(false,StatusCode.ERROR, e.getMessage());     } }

有的时候,我们需要业务逻辑时抛出自定义异常,这个时候需要自定义业务异常类

1、定义类,返回异常结果信息

public class Result {
	private Integer code;
	private String msg;

	public Result(Integer code,String msg) {
		this.code = code;
		this.msg = msg;
	}

	public Integer getCode() {
		return code;
	}

	public String getMsg() {
		return msg;
	}
}

2.定义一个业务异常类
说明:因为某些业务需要进行业务回滚。但spring的事务只针对RuntimeException的进行回滚操作。所以需要回滚就要继承RuntimeException。

public class BusinessException extends RuntimeException{

	private static final long serialVersionUID = 1L;

	private Integer code; //错误码

	public BusinessException() {}

	public BusinessException(Result result) {
		super(result.getMsg());
		this.code = result.getCode();
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}
}

3.定义一个全局异常处理类

@ControllerAdvice
public class GlobalDefultExceptionHandler {

	// 捕捉UnauthorizedException
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	@ExceptionHandler(UnauthorizedException.class)
	
	public ModelAndView handleUnauthorizedException(HttpServletResponse resp,HttpServletRequest req,UnauthorizedException e) {
   		logger.error(e.getMessage(),e);
		return ResultUtil.error(ResultEnum.CODE_403,errors.toString());
	}
	
	//声明要捕获的异常(自定义异常和Exception)
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public <T> Result<?> defultExcepitonHandler(HttpServletRequest request,Exception e) {
e.printStackTrace();
		if(e instanceof BusinessException) {
			Log.error(this.getClass(),"业务异常:"+e.getMessage());
			BusinessException businessException = (BusinessException)e;
			return ResultUtil.error(businessException.getCode(), businessException.getMessage());
		}
//未知错误
		return ResultUtil.error(-1, "系统异常:\\n"+e);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值