Summary of processing architecture of Java restful back-end Exception __exception

Source: Internet
Author: User
Tags aop class definition stringbuffer

This paper mainly combines the implementation of the Restfuljava back-end to summarize the exception processing architecture.

1. Classification and processing methods of exception

Exception is a very important feature of object-oriented language, and good exception design is crucial to the scalability, maintainability and robustness of the program.
Java defines two types of exceptions, depending on their usefulness
Checked Exception:exception Subclass, the declaration to display on the method signature throws, the compiler forces the caller to handle such an exception or declare that the throws continues to throw up.
Unchecked Exception:runtimeexception, the method signature does not need to declare throws, nor does the compiler force the caller to handle the class exception.

We are going to talk about the checkedexception:

Application-Level exception: The exception that is thrown by the application in operation, is mainly related to the business logic of the application, and these exception are defined in the application, such as: Enter the login account cannot find, login failed.

System-Level exception: Application of exceptions thrown by the system during operation, such as IO errors, arithmetic errors, and so on.

All I want to talk about is the handling of these two types of exception.

2. How to define and use a centralized exception handler

System Exception:exception and SQL Exception

Business exception:badrequestexception, Notfoundexception,serverrejectexception, SystemException

These Exception can be thrown anywhere in the restful back-end system, with spring's Exception handler to centralize all the thrown Exception

@ControllerAdvice public class Globalexceptioncontroller {private static final Log logger = logfactory. GetLog (Global

	Exceptioncontroller.class); @ExceptionHandler (Sqlexception.class) @ResponseStatus (value = httpstatus.internal_server_error) public Modelandview
		Handlesqlexception (HttpServletRequest request, SQLException ex) {handlelog (request, ex);
		map<string, object> errormap = new hashmap<string, object> ();
		Errormap.put ("code", Httpstatus.internal_server_error);
		Errormap.put ("Requested", Request.getrequesturl ());

		Errormap.put ("Message", ex.tostring ());
	return new Modelandview (Jsonutils.view_name, Jsonstringview.json_model_data, Errormap); @ExceptionHandler (Badrequestexception.class) @ResponseStatus (value = httpstatus.bad_request) public Modelandview ha
		Ndlebadrequestexception (HttpServletRequest request, badrequestexception ex) {handlelog (request, ex); Exceptionmodel Exceptionmodel = Getexceptionmodel (Httpstatus.bad_request, ex);
	return new Modelandview (Jsonutils.view_name, Jsonstringview.json_model_data, Exceptionmodel); @ExceptionHandler (Serverrejectexception.class) @ResponseStatus (value = httpstatus.forbidden) public Modelandview ha
		Ndleserverrejectexception (HttpServletRequest request, serverrejectexception ex) {handlelog (request, ex);
		Exceptionmodel Exceptionmodel = Getexceptionmodel (Httpstatus.forbidden, ex);
	return new Modelandview (Jsonutils.view_name, Jsonstringview.json_model_data, Exceptionmodel); @ExceptionHandler (Notfoundexception.class) @ResponseStatus (value = httpstatus.not_found) public Modelandview handle
		Notfoundexception (HttpServletRequest request, notfoundexception ex) {handlelog (request, ex);
		Exceptionmodel Exceptionmodel = Getexceptionmodel (Httpstatus.not_found, ex);
	return new Modelandview (Jsonutils.view_name, Jsonstringview.json_model_data, Exceptionmodel); } @ExceptionHandler (Systemexception.class) @ResponseStatus (value = Httpstatus.internal_server_error) public Modelandview handlesystemexception (HttpServletRequest request,
		SystemException ex) {handlelog (request, ex);
		Exceptionmodel Exceptionmodel = Getexceptionmodel (Httpstatus.internal_server_error, ex);
	return new Modelandview (Jsonutils.view_name, Jsonstringview.json_model_data, Exceptionmodel); @ExceptionHandler (Exception.class) @ResponseStatus (value = httpstatus.internal_server_error) public Modelandview ha
		Ndleallexception (HttpServletRequest request, Exception ex) {handlelog (request, ex);
		map<string, object> errormap = new hashmap<string, object> ();
		Errormap.put ("Code", Integer.valueof (HttpStatus.INTERNAL_SERVER_ERROR.value ()));
		Errormap.put ("Message", ex.tostring ());

	return new Modelandview (Jsonutils.view_name, Jsonstringview.json_model_data, Errormap); Private Exceptionmodel Getexceptionmodel (Httpstatus httpstatus, commonexception ex) {Exceptionmodel ExceptionMod el = new ExcepTionmodel ();
		Errorenum errorenum = Ex.geterrorenum ();
		Exceptionmodel.setstatus (Httpstatus.value ());
		Exceptionmodel.setmoreinfo (Ex.getmoreinfo ());
			if (errorenum!= null) {Exceptionmodel.seterrorcode (Errorenum.getcode ());
		Exceptionmodel.setmessage (Errorenum.tostring ());
	return Exceptionmodel;
		} private void Handlelog (HttpServletRequest request, Exception ex) {Map parameter = Request.getparametermap ();
		StringBuffer logbuffer = new StringBuffer ();
			if (request!= null) {logbuffer.append ("request Method=" + Request.getmethod ());
		Logbuffer.append ("url=" + Request.getrequesturl ());
		} if (ex instanceof commonexception) {logbuffer.append ("moreinfo=" + ((commonexception) ex). Getmoreinfo ());
		} if (ex!= null) {Logbuffer.append ("exception:" + ex);
	} logger.error (Logbuffer.tostring ()); }

}


To get a closer look, here's a reference.

http://www.journaldev.com/2651/ Spring-mvc-exception-handling-exceptionhandler-controlleradvice-handlerexceptionresolver-json-response-example

3. Exception return design for HTTP request

Design different return messages and ErrorCode in each application exception:

And the status of the return is also different.

There are mainly two different ways to return errors for restful interface:


The first type of Facebook, whether normal return or error return, Httpstatus is OK, return information need check returned object

For the second Twilio and SimpleGeo, HTTP status returns 200 normally, error returns 400,404, 403, and so on.

The author adopts the second way.

Return value selection for Http status:

According to the specific situation of restful application, the author mainly chooses:

· 200–ok

· 400-bad Request

· 403–forbidden

· 404–not Found

· 503–internal Servererror


Restful returns the model class definition for the error information:

Public Classexceptionmodel {
    private Integer status;  
    Private Integer errorcode;
    private String message;
    Private String moreinfo;
   
   
    Public Integer GetErrorCode () {return
        errorcode;
    }
    public void Seterrorcode (Integer errorcode) {
        this.errorcode = errorcode;
    }
    Public Integer GetStatus () {return
        status;
    }
    public void SetStatus (Integer status) {
        this.status = status;
    }
    Public String GetMessage () {return message
        ;
    }
    public void Setmessage (String message) {
        this.message = message;
    }
    Public String Getmoreinfo () {return
        moreinfo;
    }
    public void Setmoreinfo (String moreinfo) {
        this.moreinfo = moreinfo;
    }
}

{
"message": "400202:the specific parameter are exist in System.",
"status": "
errorcode": 400202,
" MoreInfo ":" 06d690e7-fb4d-45a8-91e0-7d82b0c60ca5 and 09f5edd6-1be3-4949-a302-9f487f82d723 ' is exist in System
}


For details, please refer to:

Https://blog.apigee.com/detail/restful_api_design_what_about_errors

4. Use spring AOP for input and return validation

@Aspect public
class Infoobjectinterceptor {
 
@Autowired
private Validatorbean Validatorbean;
 
Private static final Log logger =logfactory
           . GetLog (infoobjectinterceptor.class);
 
@Pointcut ("Execution (* com.json.BeanLang.createInfoObject (..))")
Private Voidcreateinfoobjectmethod () {
}//
 
 
@Before ("Createinfoobjectmethod () && args ( Infoobjectmodel) ") Public
Voiddoaccesscreatecheck (Infoobjectmodel Infoobjectmodel)
           throws Exception {
      if (validatorbean.checkinfoobjectexist (infoobjecid)) {
           String moreinfo = Newstringbuffer ()
                    . Append ( INFOOBJECID)
                    . Append ("Isexist in System"). ToString ();
           Throw newbadrequestexception (
                    errorenum.parameter_exist_in_system,moreinfo);}}   
 


Spring AOP can refer to:
http://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/

5. Principles and techniques of exception handling

Reference: http://lavasoft.blog.51cto.com/62575/18920/

1, avoid too large try block, do not put the exception code into the try block, try to keep a try block corresponding to one or more exceptions.
2, the type of refinement of the exception, do not matter what type of exceptions are written excetpion.
3, catch block as far as possible to maintain a block to catch a class of exceptions, do not ignore the catch of the exception, caught after either processing, or translation, or to throw out the new type of exception.
4. Do not throw away the exception that you can handle.
5, do not use Try...catch to participate in the program process, the basic purpose of exception control is to deal with the abnormal situation of the program

6. Advantages

A Business information feedback to the client, facilitate system integration and debugging

B System-level exception in favor of function tests discovering hidden bugs

Reference:

http://mariuszprzydatek.com/2013/07/29/spring-localized-exception-handling-in-rest-api/

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.