springmvc 全局异常ControllerAdvice、ExceptionHandler

springmvc框架采用的是统一、全局的异常处理。把controller中的所有异常处理都集中到一个地方。采用的是AOP的思想、把业务逻辑和异常处理代码分开,降低耦合。Springmvc中的异常处理主要用到以下两个注解@ControllerAdvice和@ExceptionHandler。

1、自定义1个异常类。

public class LzsException extends RuntimeException {

	private static final long serialVersionUID = 9053285379587890690L;

	protected int errCode;
	protected String errMsg;
	protected Throwable errCause;
	
	public LzsException() {
		super();
	}

	public LzsException(String errMsg) {
		super(errMsg);
		this.errMsg = errMsg;
	}

	public LzsException(Throwable errCause) {
		super(errCause);
		this.errCause = errCause;
	}

	public LzsException(String errMsg, Throwable errCause) {
		super(errMsg,errCause);
		this.errMsg = errMsg;
		this.errCause = errCause;
	}

	public LzsException(int errCode, Throwable errCause) {
		super();
		this.errCode = errCode;
		this.errCause = errCause;
	}
	
}

2、定义个普通类,作为全局异常处理类

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public HttpJsonResponse exceptionHandler(Exception e){
        log.error("Exception:{}",e.getMessage());
        HttpJsonResponse result = new HttpJsonResponse();
        result.setCode(ResponseConst.ErrorCode.ERR_999);
        result.setMessage("服务器内部错误,请联系管理员");
        return result;
    }

    @ExceptionHandler(LzsException.class)
    @ResponseBody
    public HttpJsonResponse lzsExceptionHandler(Exception e){
        log.error("LzsException异常:{}",e.getMessage());
        HttpJsonResponse result = new HttpJsonResponse();
        result.setCode(ResponseConst.ErrorCode.ERR_999);
        result.setMessage(e.getMessage());
        //1可以吧异常信息记录下来保存到数据库,
        //2发送通知,把异常信息通过邮件,短信,微信发给相关人员。
        //3返回前端友好提示
        return result;
    }
}

3、通过Controller调用service层业务接口,service层抛出异常:

if (CollectionUtils.isEmpty(unionIdList)) {
			throw new LzsException("请联系管理员设置xxx");
		}

4、如果没起作用,可以排查以下两个方便。

        4.1检查是否在配置文件application.xml里有这样的配置,如果没有需要加上:

<mvc:annotation-driven />
<context:component-scan base-package="com.lzs" />

        4.2 检查controller层是否加了try...catch  .有则去掉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猩猩之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值