In yesterday’s post I shared with you about exception handling in SpringBoot. I mentioned that exceptions thrown by filters cannot be caught by exception handling classes. Then my friend asked me how to handle exceptions.
There are several ways to deal with this problem, so I will briefly share the way I dealt with it in a recent project.
Exception processing roadmap in Filter
First of all, we should understand that in the filter we generally do not write very long business logic, generally do some basic parameters or permissions verification, so there will not be too complex code.
Since we know that the length of the code is controllable, we can strictly use try and catch in the filter where exceptions may occur, and then forward the request to the corresponding Controller to return the JSON data we need.
First let’s define an ErrorController for error returns.
@RequestMapping(value = "/ 401") public Object notLogin(HttpServletRequest Request) {Exception errorMessage = (Exception) request.getAttribute("errorMessage");
String message = errorMessage.getMessage();
System.out.println(message);
return "Not logged in";
}
Copy the code
Next, in the Filter, simulate an exception and forward the request to our custom ErrorController.
@WebFilter(filterName = "baseFilter", urlPatterns = "/ *")
public class BaseFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Initialize the filter...");
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; try { int i = 0 / 0; } catch (Exception e) {// Encapsulate the error message in request request.setattribute ("errorMessage", e); / / request forwarding request. GetRequestDispatcher ("/ 401").forward(req, resp); } filterChain.doFilter(req, resp); }}Copy the code
You can handle exceptions in the filter in the simple way above.
Note:
1, at the time of forwarding the request, use the request as far as possible. The getRequestDispatcher (” / 401 “). The forward (the req, resp); This mode will only be forwarded within the server, the client address does not change; If you use Response.sendreDirect (“/401”); Request forwarding, the client address will change, I stepped on this pit, adjust the interface Android teacher has cross-domain problems, is caused by this.
2. If you are using Filter for the first time in your SpringBoot project, make sure to annotate @ServletComponentScan on the startup class, otherwise Filter will not work.
All right, that’s it for today.