SPRINGMVC Learning (9)-Global exception handling

Source: Internet
Author: User

First, abnormal handling ideas:

There are two kinds of exceptions in the system: expected exception and run-time exception runtimeexception, the former obtains exception information by catching exception, the latter mainly by standardizing code development, testing through means to reduce the occurrence of run-time exception.

The DAO, service, controller of the system is thrown up through throws exception, and finally by the SPRINGMVC Front controller to the exception processor for exception processing, such as:

SPRINGMVC provides a global exception handler (a system with only one exception handler) for uniform exception handling.

Second, custom exception class inheritance exception

1  Packagecom.cy.exception;2 3 /**4 * System Custom Exception class, for the expected exception, you need to throw such an exception in the program5  * @authorChengyu6  *7  */8  Public classCustomexceptionextendsexception{9     Ten      PublicString message; One      A      Publiccustomexception (String message) { -         Super(message); -          This. Message =message; the     } -  -      PublicString getMessage () { -         returnmessage; +     } -  +      Public voidsetmessage (String message) { A          This. Message =message; at     } -}
customexception

Third, global exception handler:

Ideas:

The system encounters an exception, is thrown manually in the program, DAO throws to the service, the service to the Controller, the controller throws to the front-end controllers, and the front controller calls the global exception handler.

Global exception handler processing ideas:

Parse out exception type

If the exception type is a system-defined exception, remove the exception information directly on the error page to display

Constructs a custom exception type if the exception type is not a system-customized exception (information is "Unknown error")

1  Packagecom.cy.exception;2 3 Importjavax.servlet.http.HttpServletRequest;4 ImportJavax.servlet.http.HttpServletResponse;5 6 ImportOrg.springframework.web.servlet.HandlerExceptionResolver;7 ImportOrg.springframework.web.servlet.ModelAndView;8 9 /**Ten * Global Exception handler One  * @authorChengyu A  * -  */ -  Public classCustomexceptionresolverImplementshandlerexceptionresolver{ the      -     /** - * Exception thrown by ex system - * Handler is the processor adapter to execute handler object (only method) +      */ - @Override +      PublicModelandview resolveexception (httpservletrequest request, A httpservletresponse Response, Object handler, Exception ex) { at          -Customexception customexception =NULL; -          -         //parse out exception type -         //If the exception type is a system-defined exception, remove the exception information directly on the error page to display -         //constructs a custom exception type if the exception type is not a system-customized exception (information is "Unknown error") in         if(exinstanceofcustomexception) { -Customexception =(Customexception) ex; to}Else{ +Customexception =NewCustomexception ("Unknown error! "); -         } the          *Modelandview Modelandview =NewModelandview (); $Modelandview.addobject ("Message", Customexception.getmessage ());Panax NotoginsengModelandview.setviewname ("Error"); -         returnModelandview; the     } +  A}
View Code

Four, error page:

1 <%@ Page Language="Java"ContentType="text/html; Charset=utf-8"2 pageencoding="UTF-8"%>3 <!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd ">4 <HTML>5 <Head>6 <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8">7 <title>Error hints</title>8 </Head>9 <Body>Ten ${message} One </Body> A </HTML>
View Code

To configure the global exception handler in Springmvc.xml:

1 <!--  -2<class = " Com.cy.exception.CustomExceptionResolver "/>
View Code

Five, test code:

Manually throw an exception at any one of the controller, service, or DAO, and manually throw the exception to display the custom error exception information on the error page;

If the exception is not manually thrown, the description is a runtimeexception; only "Unknown error" is displayed on the error page;

1) Throw an exception in the controller:

1@RequestMapping (value= "/edititems", method={requestmethod.post,requestmethod.get})2      PublicString Edititems (model, @RequestParam (value= "id", required=true, defaultvalue= "4") Integer items_id)throwsexception{3Itemscustom Itemscustom =Itemsservice.finditemsbyid (items_id);4         5         if(Itemscustom = =NULL){6             Throw NewCustomexception ("Product information does not exist! ");7         }8         9Model.addattribute ("Items", itemscustom);Ten          One         return"Items/edititems"; A}
View Code

2) Throw an exception in the service:

1 @Override2      PublicItemscustom Finditemsbyid (Integer ID)throwsException {3Items items =Itemsmapper.selectbyprimarykey (ID);4         5         if(Items = =NULL){6             Throw NewCustomexception ("The product information does not exist AH!" ");7         }8         9Itemscustom Itemscoustom =NULL;Ten         if(items!=NULL){ OneItemscoustom =NewItemscustom (); A beanutils.copyproperties (items, itemscoustom); -         } -          the         returnItemscoustom; -}
View Code

Program run to throw exception will jump out of the method, no longer executed;

If an exception is associated with a business function, it is recommended that an exception be thrown in the service.

Exceptions that are not related to business functions are recommended to be thrown in the controller.

The above feature, it is recommended to throw an exception in the service.

SPRINGMVC Learning (9)-Global exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.