Exception handling:
This is the 14th day of my participation in the August Text Challenge.More challenges in August
Background:
Recently, when I set up my own personal blog (code farmer xiao Bai’s obsession), the first thing I thought about when I set up my own backend was exception handling. I am also learning while doing, it is inevitable that there are omissions, I hope friends in the wrong place to remind.
Technology stack:
- SpringBoot 2.5.3
- Mybatis-plus
- thymeleaf
- mysql
This blog simply records their learning process, if the following to make a simple demo, then will sort out the details published.
Exception handling
Based on my rough learning and understanding, I divided the abnormal errors into three parts: 4xx, 5XX and error(custom).
404 and 500 responses are commonly used
- 404 (Not found) The server could not find the requested page
- Server internal error The server encountered an error and could not complete the request
Create 404.html, 500.html, and error.html in the templates file
If you create 4xx.html and 5xx.html, then when the page is not found or the program internal error, SpringBoot automatically matches the two pages, the specific source code here is not analyzed, interested can go to learn.
What do I say when I want to return an error message to my custom page?
We think from the top down:
- When we visit the page, whether the page error, can not find, is not to go to the Url it requested, then how do we deal with this request?
- We naturally think of interceptors, at the moment, so write ControllerExceptionHandler class, to intercept all exceptions request.
- When we’re done with the exception, we can either cast the line or return it to the custom page we need.
This fulfils our above requirements.
Technical points required:
-
@ControllerAdvice
- Combined with the @ExceptionHandler annotation, when an exception is thrown to the Controller layer, the exception can be uniformly processed by specifying the JSON format to be returned or redirecting to the specified error page.
-
@ExceptionHandler(exception.class) // All exceptions are caught
-
ModelAndView is just two things: one is to specify the page to return, and the other is to add properties to the page
Obtain the related abnormal information by printing the Logger:
// Get the exception information
logger.error(() -> {
return String.format("Request URL : %s,Exception : %s ", request.getRequestURL(),e);
},e);
Copy the code
Here oneself walked a few detours, the young man oneself walked narrow, guide a package to pour wrong 😂. Here I guide the package is mybatis:
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
Copy the code
Pass the parameter has been wrong, can only go to the source way, see what they call: finally write the above code format.
When I looked at other people’s code, it dawned on me:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
logger.error("Requst URL: {}, Exception: {}", request.getRequestURL(),e);
Copy the code
Maybe some friends feel nothing, but IT took me half an hour to come out, the food is the original sin.
The Logger is just going to output to the console, or it’s bound to the log, and it’s going to output to the log.
The above problem is then implemented through the ModelAndView class:
ModelAndView looks a lot like Model.
ModelAndView modelAndView = new ModelAndView(); // Instantiate a ModelAndView
modelAndView.addObject("url",request.getRequestURL()); // Add the obtained URL to the model
modelAndView.addObject("exception",e); // Obtain the exception information
// Return to the error page
modelAndView.setViewName("error/error");
return modelAndView;
Copy the code
Knock on the blackboard: New demand!
What if I wanted to strip the 404 exception out of all the exceptions and give it back to SpringBoot to handle the page automatically?
In terms of learning. When the page is null, a custom exception class is thrown up that marks the exception status.
throw new NotFoundException("Unable to find blog, please contact administrator."); // Custom class
Copy the code
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{
public NotFoundException(a) {
super(a); }public NotFoundException(String message) {
super(message); }}Copy the code
. Then we can pass in the general exception AnnotationUtils findAnnotation through afferent AnnotatedElement and annotation types for the annotation on the method or class object.
If the conditions are met, an exception can be thrown for SpringBoot to take over.
if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) ! =null) {
throw e;
}
Copy the code
The specific code can be viewedGithub
The end:
If you see here or just to help you, hope to point a concern or recommendation, thank you;
There are mistakes, welcome to point out in the comments, the author will see the modification.