How the exception is handled in the project is usually done by inheriting exception or implementing the Runnable interface to encapsulate the custom exception, and then capturing the occurrence of the exception in the project code through the TRY...CATCH statement block, encapsulated in our own defined exception class. If the project is used in the SPRINGMVC framework, here is another more convenient exception handling methods, I still prefer this approach. Here is the annotation of Exceptionhandler. 1, first create a new abstract class named Basecontroller;
Public
Abstract
class Basecontroller { @ExceptionHandler
Public String Exception (HttpServletRequest Request, Exception e) { //different processing according to different exception types
if(e
instanceof SQLException) {String s = "Database Exception" ; Request. SetAttribute ( "Exceptionmessage", s);
return "Error"; }
Else
if(e
instanceof IOException) {String s = "IO exception"; Request. SetAttribute ( "Exceptionmessage", s);
return "Error"; }
Else
return "Error"; }}The method needs to be defined inside the controller, then create a method and decorate it with @exceptionhandler annotations to handle the exception, which is basically the same method as @RequestMapping modification, Only one parameter of type exception can be added, and the type of one or more exceptions, @ExceptionHandler, is considered to trigger all exception type errors, and the return value is the view name.2, after each controller class to inherit the definition of Basecontroller can;
@Controller@RequestMapping(value="/login" )
Public
class Logincontroller
extends basecontroller{
Private Logger Logger = Logger.
GetLogger (Logincontroller.
class);
Private Jsongenerator
Jsongenerator =
NULL; @AutowiredIuserservice UserService; @RequestMapping(value= "/login")
Public String Login ()
throws exception{ Logger. Info ( "Login ....");//Simulate throwing a SQL exception message here
Throw
New SQLException (); }}3. Finally define a error.jsp page<%@ page language =
"Java" ContentType=
"text/html; Charset=utf-8 " pageencoding=
"Utf-8"%> <%@taglib prefix =
"C" URI=
"Http://java.sun.com/jsp/jstl/core" %><HTML> <Body >${exceptionmessage} </Body ></HTML>Operating Effect:
Of course, if you are accustomed to using a configuration file partner, you can also use the spring configuration file to implement.
SPRINGMVC using annotations for exception handling