Absrtact: Original Creation Place Http://peijie2016.oschina.io welcome reprint, Keep abstract, thank you.
In a spring MVC project, using uniform exception handling makes it easy to maintain code. Here is a summary of the 3 commonly used methods. implementing the Handlerexceptionresolver interface
Implements the Handlerexceptionresolver interface, implements the Resolveexception () method, and makes processing based on the type of exception passed in. inheriting the Abstracthandlerexceptionresolver class
Inheriting the Abstracthandlerexceptionresolver class is similar to the first, because Abstracthandlerexceptionresolver implements the Handlerexceptionresolver interface.
So, after we inherit, we also rewrite the Resolveexception () method to handle various exceptions. Working with annotations @controlleradvice
It is recommended to use this method, more intuitive. The following code:
The first is the custom exception class
public class Resourcedoesnotexistexception extends RuntimeException {
private static final long Serialversionuid = 78 33283455112352655L;
Public resourcedoesnotexistexception () {
super ();
}
Public resourcedoesnotexistexception (String message) {
super (message);
}
Public resourcedoesnotexistexception (String message, throwable cause) {
Super (message, cause);
}
Public resourcedoesnotexistexception (Throwable cause) {
super (cause);
}
Protected resourcedoesnotexistexception (String message, Throwable cause, Boolean enablesuppression, Boolean Writablestacktrace) {
super (message, cause, enablesuppression, writablestacktrace);
}
}
Then there is the global Exception uniform processing class:
@ControllerAdvice public
class Globalexceptionhandler {
@ExceptionHandler (value = otherexception.class) Public
Modelandview Defaulterrorhandler (httpservletrequest req, Exception ex) {
//Other exception handling logic ...
}
@ExceptionHandler (value = resourcedoesnotexistexception.class) public
Modelandview Notfounderrorhandler ( HttpServletRequest req, resourcedoesnotexistexception ex) {
Modelandview Mav = new Modelandview ();
Mav.setviewname ("404");
return MAV;
}
}
The class that adds @controlleradvice annotations is where the exception is handled centrally, and multiple such classes can exist at the same time for finer-grained partitioning.
In this class, we can write a processing logic for each exception, using the @exceptionhandler annotation adornment on the method, passing in the specified exception type.
If it's a restful style, don't return to the view, you can also use @restcontrolleradvice.