背景介绍
开发一个前后端分离的项目时,使用了SpringMVC中的interceptor进行请求参数校验。例如将头部中的token放在session中,供后续业务逻辑访问;同时,所有请求使用通用包装返回类R包装。
如果请求中没有token header,程序会抛出默认的错误ServletRequestBindingException,客户端获得的json返回也不优雅。因此,注册一个如下的自定义处理器,可以解决抛出的此类异常。
package com.emgc.emergency.exc;
import com.emgc.emergency.common.R;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class RespExceptionHandler {
@ExceptionHandler(ServletRequestBindingException.class)
public R handleServletRequestBindingException(ServletRequestBindingException e) {
return R.err(e.getMessage());
}
}
便可以优雅进行异常拦截和http返回。
{ "code": -1, "msg": "Missing session attribute 'id' of type String", "data": null }