springMVC support for exception handling
No matter what project you are doing, exception handling is very necessary, and you cannot throw some error codes that only programmers can understand to users, so at this time, perform unified exception handling to show a comparison Friendly error pages are necessary. Like other MVC frameworks, springMVC also has its own exception handling mechanism.
There are two main ways to handle exceptions provided by springMVC. One is to directly implement your own HandlerExceptionResolver. Of course, this also includes using the SimpleMappingExceptionResolver and DefaultHandlerExceptionResolver that Spring has provided us. The other is to use annotations to implement a specialized Controller for handling exceptions - ExceptionHandler.
1. Implement your own HandlerExceptionResolver. HandlerExceptionResolver is an interface. springMVC itself already has its own implementation-DefaultHandlerExceptionResolver. This resolver is just for Some of the more typical exceptions are intercepted and then the corresponding error codes are returned. Of course, you can also inherit the DefaultHandlerExceptionResolver class and then rewrite some of the exception handling methods to implement your own exception handling.
The fourth of the above resolveException The parameter indicates which type of exception is handled. Because the Exception class is the base class of all exception classes, if you want to perform different processing according to different exception types, you can perform different processing according to different exception types in the resolveException method and return different exception views. For example:
public class ExceptionHandler implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { // TODO Auto-generated method stub if (ex instanceof NumberFormatException) { //doSomething... return new ModelAndView("number"); } else if (ex instanceof NullPointerException) { //doSomething... return new ModelAndView("null"); } return new ModelAndView("exception"); } }
After defining such an exception handler, you must define such a bean object in the applicationContext, such as:
nbsp;HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <base>"> <title>My JSP 'number.jsp' starting page</title> <meta> <meta> <meta> <meta> <meta> <!-- <link rel="stylesheet" type="text/css" href="styles.css?1.1.11"> --> NumberFormatException. <br> <br> <br><span><!-- 这是JSP中的内置对象exception --></span> <br><span><!-- 这是SpringMVC放在返回的Model中的异常对象 --></span> <span><!-- HttpServletResponse返回的错误码信息,因为前面已经配置了NumberFormatException的错误码返回值为888,所以这里应该显示888 --></span>
(4)当请求/test/number.do的时候会返回定义好的number视图,返回结果如下:
2、使用@ExceptionHandler进行处理
使用@ExceptionHandler进行处理有一个不好的地方是进行异常处理的方法必须与出错的方法在同一个Controller里面
如:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import com.tiantian.blog.web.servlet.MyException; @Controller public class GlobalController { /** * 用于处理异常的 * @return */ @ExceptionHandler({MyException.class}) public String exception(MyException e) { System.out.println(e.getMessage()); e.printStackTrace(); return "exception"; } @RequestMapping("test") public void test() { throw new MyException("出错了!"); } }
这里在页面上访问test方法的时候就会报错,而拥有该test方法的Controller又拥有一个处理该异常的方法,这个时候处理异常的方法就会被调用
优先级
既然在SpringMVC中有两种处理异常的方式,那么就存在一个优先级的问题:
当发生异常的时候,SpringMVC会如下处理:
(1)SpringMVC会先从配置文件找异常解析器HandlerExceptionResolver
(2)如果找到了异常异常解析器,那么接下来就会判断该异常解析器能否处理当前发生的异常
(3)如果可以处理的话,那么就进行处理,然后给前台返回对应的异常视图
(4)如果没有找到对应的异常解析器或者是找到的异常解析器不能处理当前的异常的时候,就看当前的Controller中有没有提供对应的异常处理器,如果提供了就由Controller自己进行处理并返回对应的视图
(5)如果配置文件里面没有定义对应的异常解析器,而当前Controller中也没有定义的话,那么该异常就会被抛出来。
The above is the detailed content of springMVC support for exception handling. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

The abnormality in the pool is a side task in the game. Many players want to know how to complete the abnormality in the pool task. It is actually very simple. First, we must master the technique of shooting in the water before we can accept the task and investigate the source of the stench. Later, we discovered It turns out that there are a lot of corpses under the pool. Let’s take a look at this graphic guide for the unusual tasks in the pool in Rise of Ronin. Guide to unusual missions in the Ronin Rise Pool: 1. Talk to Iizuka and learn the technique of shooting in the water. 2. Go to the location in the picture below to receive the abnormal task in the pool. 3. Go to the mission location and talk to the NPC, and learn that there is a foul smell in the nearby pool. 4. Go to the pool to investigate. 5. Swim to the location in the picture below, dive underwater, and you will find a lot of corpses. 6. Use a camera to take pictures of the corpse. 7

Today I would like to introduce to you an article published by MIT last week, using GPT-3.5-turbo to solve the problem of time series anomaly detection, and initially verifying the effectiveness of LLM in time series anomaly detection. There is no finetune in the whole process, and GPT-3.5-turbo is used directly for anomaly detection. The core of this article is how to convert time series into input that can be recognized by GPT-3.5-turbo, and how to design prompts or pipelines to let LLM solve the anomaly detection task. Let me introduce this work to you in detail. Image paper title: Largelanguagemodelscanbezero-shotanomalydete

In the process of PHP development, dealing with special characters is a common problem, especially in string processing, special characters are often escaped. Among them, converting special characters into single quotes is a relatively common requirement, because in PHP, single quotes are a common way to wrap strings. In this article, we will explain how to handle special character conversion single quotes in PHP and provide specific code examples. In PHP, special characters include but are not limited to single quotes ('), double quotes ("), backslash (), etc. In strings

Exception handling and unit testing are important practices to ensure the soundness of C++ code. Exceptions are handled through try-catch blocks, and when the code throws an exception, it jumps to the catch block. Unit testing isolates code testing to verify that exception handling works as expected under different circumstances. Practical case: The sumArray function calculates the sum of array elements and throws an exception to handle an empty input array. Unit testing verifies the expected behavior of a function under abnormal circumstances, such as throwing an std::invalid_argument exception when an array is empty. Conclusion: By leveraging exception handling and unit testing, we can handle exceptions, prevent code from crashing, and ensure that the code behaves as expected under abnormal conditions.

JUnit is a widely used Java unit testing framework in Spring projects and can be applied by following steps: Add JUnit dependency: org.junit.jupiterjunit-jupiter5.8.1test Write test cases: Use @ExtendWith(SpringExtension.class) to enable extension, use @Autowired inject beans, use @BeforeEach and @AfterEach to prepare and clean, and mark test methods with @Test.

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.
