最近在维护一个模块的API时,发现Controller中,如果参数在某些情况下,解析会产生异常。
一方面是代码考虑不周全,待完善。另一方面因为是API,只负责正确数据的处理,所以大部分异常都是参数没有按照正确的格式传入造成的。
所以 @ControllerAdvice 可以很好的捕获前台层面的异常。
1.创建一个java类,并加入注解。如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22import com.lwl.api.service.common.bean.ResultCode;
import com.lwl.api.service.common.bean.ResultInfo;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
@ExceptionHandler(Exception.class)
public ResultInfo signException(Exception ex) {
ResultInfo resultInfo=new ResultInfo();
resultInfo.setData("参数或格式错误");
resultInfo.setResultCode(ResultCode.Exception);
resultInfo.setMsg("异常信息:"+ex.getMessage());
return resultInfo;
}
}
2.记得在XML文件里,扫描到该文件包1
2<context:annotation-config/>
<context:component-scan base-package="com.***.***"/>
PS:
如果以上代码,没有捕获成功。可以在 @ControllerAdvice 上面再加一个@EnableWebMvc 的注解。1
2@EnableWebMvc
@ControllerAdvice
—————20171208更新线————–
最近的在更新一个SpringBoot项目,发现boot项目大量使用注解完成配置。这个项目也是API项目,但是返回值不太一样,都继承一个类,和之前的泛型类很不一样。就在这个方法上扩展了下。
这是SpringBoot的配置:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53@ControllerAdvice
public class GlobalExceptionHandler {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private RequestMappingHandlerMapping handlerMapping;
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
@ExceptionHandler(Exception.class)
public ResultBase signException(HttpServletRequest request, Exception e) {
String resultMsg="操作异常:";
Map map = this.handlerMapping.getHandlerMethods();
String path= request.getServletPath();
Iterator<?> iterator = map.entrySet().iterator();
boolean flag=true;
while(iterator.hasNext()&&flag){
Map.Entry entry = (Map.Entry) iterator.next();
RequestMappingInfo info= (RequestMappingInfo)entry.getKey();
Set<String> set= info.getPatternsCondition().getPatterns();
for(String c:set){
if(path.equals(c)){
HandlerMethod handlerMethod=(HandlerMethod) entry.getValue();
Method method = handlerMethod.getMethod();
boolean isToken = method.isAnnotationPresent(ApiOperation.class);
if (isToken){
ApiOperation annotation = method.getAnnotation(ApiOperation.class);
resultMsg=annotation.value()+"失败:";
}
String err= handlerMethod.getBean().toString()+"."+method.getName()+" error";
logger.error(err, e);
flag=false;
}
}
}
ResultBase resultBase=new ResultBase(OperInfoEnum.oper_fail, resultMsg+e);
return resultBase;
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResultBase signException(MissingServletRequestParameterException e) {
ResultBase resultBase=new ResultBase(OperInfoEnum.oper_null,"参数为空:"+e.getParameterName());
return resultBase;
}
}
主要是细分了异常类的处理,和从Spring中获取所有的Mapping定位到具体的Controller(这里暂时没找到直接定位的方法),反射拿到注解上的参数,更友好的提示。
参考资料: