Day133. Exception handling - spring MVC

exception handling

1. Overview of exception handling

  • Spring MVC handles exceptions of the program through HandlerExceptionResolver, including Handler mapping, data binding and exceptions occurring during the execution of the target method.

  • Implementation class of HandlerExceptionResolver provided by spring MVC

2. HandlerExceptionResolver

Dispatcher servlet default assembled HandlerExceptionResolver:

① Not configured with < MVC: annotation driven / >:

② The < MVC: annotation driven / > configuration is used:

3. Experimental code

① Page links

<a href="testExceptionHandlerExceptionResolver?i=1">testExceptionHandlerExceptionResolver</a>

② Controller method

@Controller
public class ExceptionHandler {
@RequestMapping("/testExceptionHandlerExceptionResolver")
    public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
    System.out.println("10/"+i+"="+(10/i));
    return "success";
    }
}

③ Test, abnormal condition

Handle the exception and jump to error jsp

④ Add a method of handling exceptions in the controller

@ExceptionHandler(value={java.lang.ArithmeticException.class})
public String handleException(Exception ex){
System.out.println("Something's wrong"+ex);
return "error";
}

⑤ Add error jsp

<h3>Error Page</h3>

4. How to carry the exception object from the controller to the page to obtain the exception information

① The exception object cannot be passed to the success page through Map collection. (Map is not allowed)

// @ExceptionHandler(value={java.lang.ArithmeticException.class})
public String handleException(Exception ex,Map<String,Object> map){
System.out.println("Something's wrong:"+ex);
map.put("exception",ex);
return "error";
}

② You can pass the exception object to the success page through ModelAndView

@ExceptionHandler(value={java.lang.ArithmeticException.class})
public ModelAndView handleException(Exception ex){
System.out.println("Something's wrong:"+ex);
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
}

5. Matching exception type and execution sequence

@ExceptionHandler(value={java.lang.ArithmeticException.class})
public ModelAndView handleException(Exception ex){
    System.out.println("Something's wrong:"+ex);
    ModelAndView mv = new ModelAndView("error");
    mv.addObject("exception", ex);
    return mv;
}
 
@ExceptionHandler(value={java.lang.RuntimeException.class})
public ModelAndView handleException2(Exception ex){
    System.out.println("RuntimeException-Something's wrong:"+ex);
    ModelAndView mv = new ModelAndView("error");
    mv.addObject("exception", ex);
    return mv;
}

6. Public exception handling class @ ControllerAdvice

① Define common exception handling classes

@ControllerAdvice
public class ExceptionAdviceHandler {
 
    /*        
    @ExceptionHandler(value={java.lang.ArithmeticException.class})
    public ModelAndView handleException(Exception ex){

    System.out.println("There is an exception: "+ ex);
    ModelAndView mv = new ModelAndView("error");
    mv.addObject("exception", ex);

    return mv; 
    }*/

    @ExceptionHandler(value={java.lang.RuntimeException.class})
    public ModelAndView handleException2(Exception ex){

    System.out.println("RuntimeException-Something's wrong:"+ex);
    ModelAndView mv = new ModelAndView("error");
    mv.addObject("exception", ex);

    return mv;
    }
}

7. ExceptionHandlerExceptionResolver

  • It mainly deals with the methods defined with the @ ExceptionHandler annotation in the Handler.

  • @The method priority problem defined by the ExceptionHandler annotation: for example, NullPointerException occurs, but the declared exceptions include RuntimeException and Exception. In this case, the @ ExceptionHandler annotation method with the shallowest inheritance depth will be found according to the nearest inheritance relationship of the Exception, that is, the method marked with RuntimeException

  • If the @ ExceptionHandler annotation cannot be found inside the ExceptionHandlerMethodResolver, the * * @ ExceptionHandler * * annotation method in @ ControllerAdvice will be found

8. Exception handling_ ResponseStatusExceptionResolver

  • Find the @ ResponseStatus annotation in the exception and exception parent class, and then use the attribute of this annotation for processing.

  • Define an exception class modified by @ ResponseStatus annotation

  • If the above exception is thrown in the processor method: if ExceptionHandlerExceptionResolver does not resolve the above exception. Due to the triggered exception, UnauthorizedException is annotated with @ ResponseStatus. Therefore, it will be resolved to by ResponseStatusExceptionResolver. Finally, respond to httpstatus Unauthorized code to the client. HttpStatus.UNAUTHORIZED means response code 401, without permission. For other response codes, please refer to the httpstatus enumeration type source code.

9. Experimental code

① Page links

<a href="testResponseStatusExceptionResolver?i=10">testResponseStatusExceptionResolver</a>

② Custom exception class

/**
 * Custom exception class
HttpStatus.FORBIDDEN Not allowed, disabled
 */
@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="The user name and password do not match")
public class UsernameNotMatchPasswordException extends RuntimeException{
}

③ Controller method

@RequestMapping(value="/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
    if(i==13){
    	throw new UsernameNotMatchPasswordException();
    }
    System.out.println("testResponseStatusExceptionResolver...");
    return "success";
}

④ Error messages that appear

  • When annotation is not used: * * @ responsestatus (value = httpstatus. * * for binding, reason = "user name and password do not match")

  • When using annotation: @ ResponseStatus(value=HttpStatus.FORBIDDEN,reason = "user name and password do not match")

  • Use annotations on test methods
@ResponseStatus(value=HttpStatus.NOT_FOUND,reason="Set the response status code on the test method")
@RequestMapping(value="/testResponseStatusExceptionResolver")
public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
    if(i==13){
 	   throw new UsernameNotMatchPasswordException();
    }
    System.out.println("testResponseStatusExceptionResolver...");
    return "success";
}

10. Exception handling_ DefaultHandlerExceptionResolver

  • Handle some special exceptions, such as:

NoSuchRequestHandlingMethodException,

HttpRequestMethodNotSupportedException,

HttpMediaTypeNotSupportedException,

HttpMediaTypeNotAcceptableException, etc.

11. Experimental code

① Add page link: GET request

<a href="testDefaultHandlerExceptionResolver">testDefaultHandlerExceptionResolver</a>

Method of adding processor

//@RequestMapping(value="/testDefaultHandlerExceptionResolver")
@RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)  //GET requests are not supported
public String testDefaultHandlerExceptionResolver(){
    System.out.println("testDefaultHandlerExceptionResolver...");
    return "success";
}

② An unexpected error occurred

12. Exception handling_ SimpleMappingExceptionResolver

  • If you want to handle all exceptions uniformly, you can use SimpleMappingExceptionResolver, which maps the exception class name to the view name, that is, when an exception occurs, the corresponding view is used to report the exception

1) Experimental code

① Add page link

<a href="testSimpleMappingExceptionResolver?i=1">testSimpleMappingExceptionResolver</a>

② Method of adding controller

@RequestMapping("/testSimpleMappingExceptionResolver")
public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
    System.out.println("testSimpleMappingExceptionResolver..."); 
    String[] s = new String[10]; 
    System.out.println(s[i]); 
    return "success";
}

③ An exception occurs: the value of parameter i is greater than 10

① Configure exception parser: automatically store the exception object information in the request range

<!-- to configure SimpleMappingExceptionResolver Exception parser -->
<bean id="simpleMappingExceptionResolver"
 class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- exceptionAttribute Default value(adopt ModelAndView Pass to page): 
exception   ->  ${requestScope.exception}
public static final String DEFAULT_EXCEPTION_ATTRIBUTE = "exception";
-->
<property name="exceptionAttribute" value="exception"></property>
    <property name="exceptionMappings">
        <props>
        	<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
        </props>
    </property>
</bean>

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> 
<h3>Error Page</h3> 
${exception }
${requestScope.exception } 
</body>
</html>

Tags: Java Spring SSM Exception

Posted by marknt on Mon, 02 May 2022 18:17:07 +0300