SpringMVC实现全局异常捕获处理

需求:在SpringMVC中实现全局异常捕获解析以及处理并且返回json状态码

需求分析解决:

1、进入Spring-MVC配置文件配置全局异常处理

 
  1. <!-- 全局异常处理 自定义实现spring的全局异常解析器HandlerExceptionResolver -->
  2. <bean id="exceptionResolver" class="com.xxx.resolver.CustomExceptionResolver"></bean>

2、定义全局异常处理类

 
  1. import java.io.IOException;
  2.  
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5.  
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.http.HttpStatus;
  9. import org.springframework.http.MediaType;
  10. import org.springframework.web.servlet.HandlerExceptionResolver;
  11. import org.springframework.web.servlet.ModelAndView;
  12.  
  13. import com.xxx.bean.Result;
  14. import com.xxx.excption.CustomException;
  15. import com.xxx.util.ResultUtils;
  16.  
  17. /**
  18. * 全局异常处理器
  19. * @author CatalpaFlat
  20. */
  21. public class CustomExceptionResolver implements HandlerExceptionResolver{
  22.  
  23. /**日志log*/
  24. private static Logger log = LoggerFactory.getLogger(CustomExceptionResolver.class);
  25.  
  26. //系统抛出的异常
  27. @Override
  28. public ModelAndView resolveException(HttpServletRequest request,
  29. HttpServletResponse response, Object handler, Exception ex) {
  30. //handler就是处理器适配器要执行的Handler对象(只有method)
  31. //解析出异常类型。
  32. /* 使用response返回 */
  33. response.setStatus(HttpStatus.OK.value()); //设置状态码
  34. response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
  35. response.setCharacterEncoding("UTF-8"); //避免乱码
  36. response.setHeader("Cache-Control", "no-cache, must-revalidate");
  37. //如果该 异常类型是系统 自定义的异常,直接取出异常信息。
  38. CustomException customException=null;
  39. try {
  40. if(ex instanceof CustomException){
  41. customException = (CustomException)ex;
  42. //错误信息
  43. response.getWriter().write(ResultUtils.error(customException.getCode(),ex.getMessage()).toString());
  44. }else
  45. response.getWriter().write(ResultUtils.error(-1,ex.getMessage()).toString());
  46. } catch (IOException e) {
  47. log.error("与客户端通讯异常:"+ e.getMessage(), e);
  48. e.printStackTrace();
  49. }
  50. ModelAndView modelAndView=new ModelAndView();
  51.  
  52. return modelAndView;
  53. }
  54.  
  55. }

3、自定义异常类CustomException

 
  1.  
  2. import com.xxx.enums.ResultEnum;
  3.  
  4. /**
  5. * 自定义异常类型
  6. * @author CatalpaFlat
  7. */
  8. public class CustomException extends Exception {
  9.  
  10. private Integer code;
  11. public CustomException(){}
  12.  
  13. public CustomException(ResultEnum resultEnum) {
  14. super((resultEnum.getMsg()));
  15. this.code = resultEnum.getCode();
  16. }
  17.  
  18.  
  19. public Integer getCode() {
  20. return code;
  21. }
  22.  
  23. public void setCode(Integer code) {
  24. this.code = code;
  25. }
  26.  
  27. }

4、定义Http响应json类

 
  1. /** 
  2. * http请求返回的最外层
  3. * Created by CatalpaFlat
  4. * on 2017/4/12.
  5. */
  6. public class Result<T> {
  7.  
  8. private Integer code;
  9.  
  10. private String msg;
  11.  
  12. private T data;
  13.  
  14. public Integer getCode() {
  15. return code;
  16. }
  17.  
  18. public void setCode(Integer code) {
  19. this.code = code;
  20. }
  21.  
  22. public String getMsg() {
  23. return msg;
  24. }
  25.  
  26. public void setMsg(String msg) {
  27. this.msg = msg;
  28. }
  29.  
  30. public T getData() {
  31. return data;
  32. }
  33.  
  34. public void setData(T data) {
  35. this.data = data;
  36. }
  37.  
  38. @Override
  39. public String toString() {
  40. return "{\"code\": "+code+",\"msg\": \""+msg+"\",\"data\": "+data+"}";
  41. }
  42.  
  43. }

5、定义http返回json的ResulUtils

 
  1.  
  2. import com.xxx.bean.Result;
  3. /** 
  4. * http请求返回success以及error方法封装
  5. * Created by CatalpaFlat
  6. * on 2017/4/12.
  7. */
  8. public class ResultUtils {
  9.  
  10.  
  11. private static final String SUCCESS_MSG = "成功";
  12.  
  13. /**
  14. * http回调成功
  15. * @param object
  16. * @return
  17. */
  18. public static Result success(Object object){
  19. Result result = new Result();
  20. result.setCode(1);
  21. result.setMsg(SUCCESS_MSG);
  22. result.setData(object);
  23. return result;
  24. }
  25.  
  26. /**
  27. * 无object返回
  28. * @return
  29. */
  30. public static Result success(){
  31. return success(null);
  32. }
  33.  
  34. /**
  35. * http回调错误
  36. * @param code
  37. * @param msg
  38. * @return
  39. */
  40. public static Result error(Integer code,String msg){
  41. Result result = new Result();
  42. result.setCode(code);
  43. result.setMsg(msg);
  44. return result;
  45. }
  46.  
  47. }

6、定义异常类型枚举ResultEnum

 
  1. /**
  2. * 枚举定义异常类型以及相对于的错误信息
  3. * 有助于返回码的唯一性
  4. * Created by CatalpaFlat
  5. * on 2017/4/12.
  6. */
  7. public enum ResultEnum {
  8.  
  9.  
  10. UNKONW_ERROR(-1,"未知错误"),
  11. SUCCESS(0,"成功"),
  12. TEST_ERRORR(100,"测试异常");
  13.  
  14. private Integer code;
  15. private String msg;
  16.  
  17. ResultEnum(Integer code,String msg){
  18. this.code = code;
  19. this.msg = msg;
  20. }
  21.  
  22. public Integer getCode() {
  23.  
  24. return code;
  25. }
  26.  
  27. public String getMsg() {
  28. return msg;
  29. }
  30. }

7、测试TestController

 
  1. @Controller
  2. @RequestMapping("/teco")
  3. public class TestController {
  4. @RequestMapping(value = "/testexc",method = RequestMethod.GET)
  5. @ResponseBody
  6. public void testException() throws CustomException{
  7. throw new CustomException(ResultEnum.TEST_ERRORR);
  8. }
  9. }

8、测试接口json返回

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DuShiWoDeCuo/article/details/70170214

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值