SPRINGMVC Study Notes (16)-Exception handler

Source: Internet
Author: User

SPRINGMVC Study Notes (16)-Exception handler

    • SPRINGMVC Learning Note 16-exception handler
      • The idea of abnormal handling
      • Custom exception Classes
      • Global exception Handler
      • Error page
      • Configuring global exception Handlers in Springmvcxml
      • Anomaly Testing

This paper mainly introduces the idea of exception handling in Springmvc, and shows how to customize exception handling class and the configuration of global exception handler.

The idea of abnormal handling

Exceptions in the system include two categories:

    • Expected exception
    • Run-time Exception runtimeexception

The former obtains the exception information by catching the exception, the latter mainly through the specification code development, the test through means reduces the run-time exception occurrence.

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.

Custom exception Classes

Defines the exception class for different exception types, inheriting exception.

 PackageCom.iot.learnssm.firstssm.exception;/** * Created by Brian on 2016/3/7. * * System Custom exception classes, for expected exceptions, you need to throw such exceptions in the program * / Public  class customexceptionextendsException{        //Exception information     PublicString message; Public customexception(String message) {Super(message); This. message = message; } PublicStringGetMessage() {returnMessage } Public void Setmessage(String message) { This. message = message; }}
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")

SPRINGMVC provides an HandlerExceptionResolver interface

    PublicModelandviewresolveexception(HttpServletRequest request, httpservletresponse response, Object handler, Exception ex) {//handler is the processor adapter to execute the handler object (only method)        //Parse out exception type        //If the exception type is a system-defined exception, simply take out the exception information and display it on the error page        //string message = NULL;        //if (ex instanceof customexception) {            //message = ((customexception) ex). GetMessage ();        //}else{            ////If the exception type is not a system-customized exception, construct a custom exception type (information is "Unknown error")            //message= "Unknown error";        //}        //The upper code becomesCustomexception customexception;if(exinstanceofcustomexception) {customexception = (customexception) ex; }Else{customexception =NewCustomexception ("Unknown error"); }//Error MessagesString message = Customexception.getmessage (); Modelandview Modelandview =NewModelandview ();//Upload error message to pageModelandview.addobject ("Message", message);//point to Error pageModelandview.setviewname ("Error");returnModelandview; }}
Error page
<%--Created by IntelliJ idea. User:brian Date: /3/4time:: Wuyi to Change this template use File | Settings | File templates.--%>    <%@ page contenttype="Text/html;charset=utf-8" language="java" %><html><head>    <title>Error hints</title></head><body>${message}</body></html>
Configuring global exception Handlers in Springmvc.xml
<!-- 全局异常处理器只要实现HandlerExceptionResolver接口就是全局异常处理器--><bean class="com.iot.learnssm.firstssm.exception.CustomExceptionResolver"></bean>

There is only one global exception handler, and it is useless to configure multiple.

Anomaly Testing

You need to throw an exception manually anywhere in the controller, service, or DAO. If the exception is manually thrown in the program, the custom exception information is displayed in the error page, and if the exception is not manually thrown, the description is a run-time exception, and only "Unknown error" is displayed on the error page.

    • Throws an exception in the controller method of the product modification.
 PublicStringEdititems(Model model,@Requestparam(value="id", required=true) Integer items_id)throwsException {//Call service to check product information based on product IDItemscustom Itemscustom = Itemsservice.finditemsbyid (items_id);//Determine whether the product is empty, according to the ID no query to the product, throw an exception, prompting the user product information does not exist    if(Itemscustom = =NULL){Throw NewCustomexception ("The modified product information does not exist!"); }//Pass model data to the page through the model in the formal parameter    //equivalent to the Modelandview.addobject methodModel.addattribute ("Items", Itemscustom);return "Items/edititems";}
    • Throw an exception in the service interface:
 PublicItemscustomFinditemsbyid(Integer ID)throwsException {Items items = Itemsmapper.selectbyprimarykey (ID);if(items==NULL){Throw NewCustomexception ("The modified product information does not exist!"); }//intermediate Business Processing of commodity information    //....    //Return to ItemscustomItemscustom Itemscustom =NULL;//Copy the Items ' property values to Itemscustom    if(items!=NULL) {Itemscustom =NewItemscustom ();    Beanutils.copyproperties (items, itemscustom); }returnItemscustom;}
    • 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.

Author @brianway More articles: personal website | CSDN | Oschina

SPRINGMVC Study Notes (16)-Exception handler

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.