A practical summary of SpringMVC exception handling

A practical summary of SpringMVC exception handling

                                                                                    - I've never really trusted my memory, so I write them all down

 

 In a web project, users need to give corresponding feedback to users when they access invalid resources, internal system errors, etc. For example, the following 404 errors, I believe the following error messages are not what users and you do not want to see.

Similar exceptions are 404, 405, 406, 500, etc. The specific meaning can be Baidu. These exception handling can allow the artist to make several beautiful pages, and then add the following in web.xml

<error-page>
        <error-code>404</error-code>
        <location>/albert/page/404</location>
    </error-page>
    <error-page>
        <error-code>405</error-code>
        <location>/albert/page/405</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/albert/page/500</location>
    </error-page>
    <error-page>
        <exception-type>org.apache.shiro.authz.AuthorizationException</exception-type>
        <location>/albert/page/401</location>
    </error-page>

 

If it is an exception thrown by the controller?

 

There are two ways to handle controller exceptions.

1. Inherit HandlerExceptionResolver, and then add this exception resolver in the mvc configuration file

/**
 * @author albert
 * Exception handling, deprecated, @ExceptionHandler is recommended </br>
 * need to be added in the mvc configuration file
 * 	<bean id="exceptionResolver" class="com.fh.resolver.MyExceptionResolver"></bean>
 */
@Deprecated
public class MyExceptionResolver implements HandlerExceptionResolver{
	Logger logger = Logger.getLogger(this.getClass());
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		ex.printStackTrace();
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));
		return mv;
	}

}

 2. In the way of annotation, an abstract class is generally defined, so that all controllers inherit it. After the controller method catches the exception, the same custom exception is thrown in the catch.

package com.albert.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
public class BaseController {  
	Logger logger = Logger.getLogger(this.getClass());
    @ExceptionHandler
    public String exception(HttpServletRequest request,HttpServletResponse res, Exception e) {  
        logger.info("Exception handling: "+e.getMessage());
        
        RestController restController = AnnotationUtils.findAnnotation(this.getClass(), RestController.class);

        if(restController==null){//Return to the page
        	request.setAttribute("exceptionMessage", e.getMessage());  
        	return "500";
        }else{ //If the controller has @RestController annotation, return json
        	PrintWriter writer = null;
			try {
				writer = res.getWriter();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
        	String json = "json_error";
        	writer.write(json);
        	writer.flush();
        	return null;
        }
    }  
    
}

 

The blogger recommends the second method to handle exceptions uniformly, the first method will be more chaotic

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326884096&siteId=291194637