详解SpringMVC中的异常处理

作者:柠檬时间 时间:2022-10-22 07:05:14 

目录
  • 1. SpringMVC默认三个异常处理类

  • 2. @ExceptionHandler注解异常

  • 3. @ResponseStatus注解异常

  • 4. DefaultHandlerExceptionResolver默认异常

  • 5. 没有找到对应异常处理类

1. SpringMVC默认三个异常处理类

  • ExceptionHandlerExceptionResolver:处理@ExceptionHandler注解

  • ResponseStatusExceptionResolver:处理@ResponseStatus注解

  • DefaultHandlerExceptionResolver:处理SpringMVC自带的异常

如果以上3个异常解析器都无法处理,会上抛给tomcat,处理异常内部的默认工作流程:所有异常解析器依次尝试解析,解析完成进行后续操作,解析失败,下一个解析器继续尝试解析。

2. @ExceptionHandler注解异常

@ExceptionHandler标注在方法上

  • 方法上写一个Exception用来接收发生的异常。

  • 要携带异常信息不能给参数位置写Model,正确的做法是返回ModelAndView。

  • 如果有多个@ExceptionHandler都能处理这个异常,精确优先。


@ExceptionHandler(value = { ArithmeticException.class, NullPointerException.class })
// 告诉SpringMVC,这个方法专门处理这个类发送的所有异常
public ModelAndView handleException01(Exception exception) {
 System.out.println("handleException01..." + exception);
 ModelAndView view = new ModelAndView("myerror");
 view.addObject("ex", exception);  
 return view;
}

@ExceptionHandler统一异常处理

  • 将@ExceptionHandler放在一个单独的类中,进行全局异常处理

  • 统一异常管理类需要通过@ControllerAdvice注解加入IoC容器中

  • 全局异常处理与本类异常处理同时存在,本类优先


@ControllerAdvice
public class MyException {
 // 处理空指针异常
 @ExceptionHandler(value = { NullPointerException.class })
 public ModelAndView handleException01(Exception exception) {
   System.out.println("全局的handleException01..." + exception);
   ModelAndView view = new ModelAndView("myerror");
   view.addObject("ex", exception);
   return view;
 }

// 处理算数异常
 @ExceptionHandler(value = { ArithmeticException.class })
 public ModelAndView handleException02(Exception exception) {
   System.out.println("全局的handleException02..." + exception);
   ModelAndView view = new ModelAndView("myerror");
   view.addObject("ex", exception);
   return view;
 }
}

3. @ResponseStatus注解异常

@ResponseStatus注解标注在自定义异常上,用于设置自定义异常信息


@ResponseStatus(reason = "用户被拒绝登录", value = HttpStatus.NOT_ACCEPTABLE)
public class UsernameNotFoundException extends RuntimeException {
 private static final long serialVersionUID = 1L;
}

4. DefaultHandlerExceptionResolver默认异常

DefaultHandlerExceptionResolver包含以下默认异常


源码:
public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionResolver {
 ...
 @Override
 protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
     Object handler, Exception ex) {

try {
     if (ex instanceof NoSuchRequestHandlingMethodException) {
       return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, request, response,
           handler);
     }
     else if (ex instanceof HttpRequestMethodNotSupportedException) {
       return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request,
           response, handler);
     }
     else if (ex instanceof HttpMediaTypeNotSupportedException) {
       return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, request, response,
           handler);
     }
     else if (ex instanceof HttpMediaTypeNotAcceptableException) {
       return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, request, response,
           handler);
     }
     else if (ex instanceof MissingPathVariableException) {
       return handleMissingPathVariable((MissingPathVariableException) ex, request,
           response, handler);
     }
     else if (ex instanceof MissingServletRequestParameterException) {
       return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, request,
           response, handler);
     }
     else if (ex instanceof ServletRequestBindingException) {
       return handleServletRequestBindingException((ServletRequestBindingException) ex, request, response,
           handler);
     }
     else if (ex instanceof ConversionNotSupportedException) {
       return handleConversionNotSupported((ConversionNotSupportedException) ex, request, response, handler);
     }
     else if (ex instanceof TypeMismatchException) {
       return handleTypeMismatch((TypeMismatchException) ex, request, response, handler);
     }
     else if (ex instanceof HttpMessageNotReadableException) {
       return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, request, response, handler);
     }
     else if (ex instanceof HttpMessageNotWritableException) {
       return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, request, response, handler);
     }
     else if (ex instanceof MethodArgumentNotValidException) {
       return handleMethodArgumentNotValidException((MethodArgumentNotValidException) ex, request, response,
           handler);
     }
     else if (ex instanceof MissingServletRequestPartException) {
       return handleMissingServletRequestPartException((MissingServletRequestPartException) ex, request,
           response, handler);
     }
     else if (ex instanceof BindException) {
       return handleBindException((BindException) ex, request, response, handler);
     }
     else if (ex instanceof NoHandlerFoundException) {
       return handleNoHandlerFoundException((NoHandlerFoundException) ex, request, response, handler);
     }
   }
   catch (Exception handlerException) {
     if (logger.isWarnEnabled()) {
       logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
     }
   }
   return null;
 }
 ...
}

如下HttpRequestMethodNotSupportedException请求方式不对。使用GET对POST方法进行访问


@RequestMapping(value = "/handle03", method = RequestMethod.POST)
public String postMethod() {
 return "success";
}

5. 没有找到对应异常处理类

若没有对应异常处理类,会进入对应服务器错误页面

来源:https://segmentfault.com/a/1190000039411231

标签:SpringMVC,异常,处理
0
投稿

猜你喜欢

  • Android获取分享应用列表详解及实例

    2023-11-17 05:47:47
  • Java面试题冲刺第五天--基础篇2

    2023-10-07 13:17:04
  • springboot redis分布式锁代码实例

    2023-12-05 21:40:10
  • 详解如何在Spring Security中自定义权限表达式

    2023-11-08 05:11:24
  • Unity 按钮事件封装操作(EventTriggerListener)

    2022-07-08 10:07:08
  • C#中抽象类与接口的区别详解

    2023-08-12 22:33:01
  • 详解在java中进行日期时间比较的4种方法

    2022-09-03 23:35:52
  • Java 多线程Synchronized和Lock的区别

    2023-08-14 11:39:09
  • Android自定义View实现公交成轨迹图

    2021-07-12 12:00:04
  • 使用 Spring Boot 2.0 + WebFlux 实现 RESTful API功能

    2023-12-22 19:51:03
  • Android自定义View实现投票进度条

    2022-04-02 13:57:21
  • springboot实现注册加密与登录解密功能(demo)

    2021-12-15 15:10:08
  • 使用Java实现Redis限流的方法

    2023-09-27 01:43:47
  • 新手初学Java数组

    2023-12-01 11:18:40
  • Android Studio 3.0中mipmap-anydpi-v26是什么东东

    2023-10-11 01:17:44
  • WPF实现雷达图(仿英雄联盟)的示例代码

    2023-07-13 18:46:53
  • Spring Cloud微服务架构的构建:分布式配置中心(加密解密功能)

    2021-10-24 05:49:59
  • 关于maven打包时的报错: Return code is: 501 , ReasonPhrase:HTTPS Required

    2022-09-09 00:50:51
  • feign客户端设置超时时间操作

    2023-07-01 19:16:32
  • Java程序员容易犯的10大低级错误

    2022-01-09 06:18:04
  • asp之家 软件编程 m.aspxhome.com