SpringMVC实现全局异常捕获处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DuShiWoDeCuo/article/details/70170214
需求:在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. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.http.HttpStatus;
  7. import org.springframework.http.MediaType;
  8. import org.springframework.web.servlet.HandlerExceptionResolver;
  9. import org.springframework.web.servlet.ModelAndView;
  10. import com.xxx.bean.Result;
  11. import com.xxx.excption.CustomException;
  12. import com.xxx.util.ResultUtils;
  13. /**
  14. * 全局异常处理器
  15. * @author CatalpaFlat
  16. */
  17. public class CustomExceptionResolver implements HandlerExceptionResolver{
  18. /**日志log*/
  19. private static Logger log = LoggerFactory.getLogger(CustomExceptionResolver.class);
  20. //系统抛出的异常
  21. @Override
  22. public ModelAndView resolveException(HttpServletRequest request,
  23. HttpServletResponse response, Object handler, Exception ex) {
  24. //handler就是处理器适配器要执行的Handler对象(只有method)
  25. //解析出异常类型。
  26. /* 使用response返回 */
  27. response.setStatus(HttpStatus.OK.value()); //设置状态码
  28. response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
  29. response.setCharacterEncoding("UTF-8"); //避免乱码
  30. response.setHeader("Cache-Control", "no-cache, must-revalidate");
  31. //如果该 异常类型是系统 自定义的异常,直接取出异常信息。
  32. CustomException customException=null;
  33. try {
  34. if(ex instanceof CustomException){
  35. customException = (CustomException)ex;
  36. //错误信息
  37. response.getWriter().write(ResultUtils.error(customException.getCode(),ex.getMessage()).toString());
  38. }else
  39. response.getWriter().write(ResultUtils.error(-1,ex.getMessage()).toString());
  40. } catch (IOException e) {
  41. log.error("与客户端通讯异常:"+ e.getMessage(), e);
  42. e.printStackTrace();
  43. }
  44. ModelAndView modelAndView=new ModelAndView();
  45. return modelAndView;
  46. }
  47. }
3、自定义异常类CustomException
  1. import com.xxx.enums.ResultEnum;
  2. /**
  3. * 自定义异常类型
  4. * @author CatalpaFlat
  5. */
  6. public class CustomException extends Exception {
  7. private Integer code;
  8. public CustomException(){}
  9. public CustomException(ResultEnum resultEnum) {
  10. super((resultEnum.getMsg()));
  11. this.code = resultEnum.getCode();
  12. }
  13. public Integer getCode() {
  14. return code;
  15. }
  16. public void setCode(Integer code) {
  17. this.code = code;
  18. }
  19. }
4、定义Http响应json类
  1. /** 
  2. * http请求返回的最外层
  3. * Created by CatalpaFlat
  4. * on 2017/4/12.
  5. */
  6. public class Result<T> {
  7. private Integer code;
  8. private String msg;
  9. private T data;
  10. public Integer getCode() {
  11. return code;
  12. }
  13. public void setCode(Integer code) {
  14. this.code = code;
  15. }
  16. public String getMsg() {
  17. return msg;
  18. }
  19. public void setMsg(String msg) {
  20. this.msg = msg;
  21. }
  22. public T getData() {
  23. return data;
  24. }
  25. public void setData(T data) {
  26. this.data = data;
  27. }
  28. @Override
  29. public String toString() {
  30. return "{\"code\": "+code+",\"msg\": \""+msg+"\",\"data\": "+data+"}";
  31. }
  32. }
5、定义http返回json的ResulUtils
  1. import com.xxx.bean.Result;
  2. /** 
  3. * http请求返回success以及error方法封装
  4. * Created by CatalpaFlat
  5. * on 2017/4/12.
  6. */
  7. public class ResultUtils {
  8. private static final String SUCCESS_MSG = "成功";
  9. /**
  10. * http回调成功
  11. * @param object
  12. * @return
  13. */
  14. public static Result success(Object object){
  15. Result result = new Result();
  16. result.setCode(1);
  17. result.setMsg(SUCCESS_MSG);
  18. result.setData(object);
  19. return result;
  20. }
  21. /**
  22. * 无object返回
  23. * @return
  24. */
  25. public static Result success(){
  26. return success(null);
  27. }
  28. /**
  29. * http回调错误
  30. * @param code
  31. * @param msg
  32. * @return
  33. */
  34. public static Result error(Integer code,String msg){
  35. Result result = new Result();
  36. result.setCode(code);
  37. result.setMsg(msg);
  38. return result;
  39. }
  40. }
6、定义异常类型枚举ResultEnum
  1. /**
  2. * 枚举定义异常类型以及相对于的错误信息
  3. * 有助于返回码的唯一性
  4. * Created by CatalpaFlat
  5. * on 2017/4/12.
  6. */
  7. public enum ResultEnum {
  8. UNKONW_ERROR(-1,"未知错误"),
  9. SUCCESS(0,"成功"),
  10. TEST_ERRORR(100,"测试异常");
  11. private Integer code;
  12. private String msg;
  13. ResultEnum(Integer code,String msg){
  14. this.code = code;
  15. this.msg = msg;
  16. }
  17. public Integer getCode() {
  18. return code;
  19. }
  20. public String getMsg() {
  21. return msg;
  22. }
  23. }
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返回

没有更多推荐了,返回首页