好久没有更新文章,最近一直在忙着代码业务,深陷短信业务泥潭。不过,昨天在维护一个API接口的时候,发现Controller层代码写的不是很严谨,在某些参数的情况下,会异常。虽然API不影响整体功能,毕竟你只要按照正确的格式输入,就能得到正确的反馈结果。但,抱着扩展能力的想法,找了找相关资料,意外获得一个新的技能点(*^__^*)
-------------------------------------我是分割线---------------------------------------------------------------
1.@ControllerAdvice 使用这个注解,可以轻松解决。上代码:
import 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;
/**
* Created by weixiang on 2016/10/31.
*/
@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文件里,扫描到该文件包
<context:annotation-config/>
<context:component-scan base-package="com.***.***"/>
3.百度
@ControllerAdvice
用法,到此就结束了。结果就是拦截不起作用,前台仍然是不友好的 500,404 的html代码。
后来,搜到再加一个注解
@EnableWebMvc
完成解决。
PS:感觉可以在这个java类中,加入日志记录,扩展功能还是很多了,靠自己的想象力啦。
参考资源:
1 《Spring3.2新注解@ControllerAdvice 》 http://jinnianshilongnian.iteye.com/blog/1866350
2.《 使用Spring MVC的@ControllerAdvice注解做Json的异常处理》 http://blog.csdn.net/cesul/article/details/38539343
3.《@EnableWebMvc》 http://www.07net01.com/linux/spring3_2_mvc__ControllerAdvice_buqizuoyong_554229_1375786240.html