SPRINGMVC return to client by exception enhancement uniform format

Source: Internet
Author: User

In the development of SPRINGMVC, we often encounter such problems, when the logic executes normally, the data in the client-specified format is returned, such as JSON, but when the nullpointerexception null pointer exception is encountered, The method called by Nosuchmethodexception does not have an exception, which is returned to the client by the server exception stack information, which causes the client not to parse the data properly; This is obviously not what we want.

Fortunately, from the new annotations provided by spring3.2 @controlleradvice, it can be seen from the name that the general meaning is controller enhancement. The principle is to use AOP to enhance controller controllers (pre-enhancement, post-enhancement, surround-enhancement, and AOP principles are self-checking); Then I am not able to handle the controller's methods before the call (pre-enhancement) and post-call (post-enhancement).

Spring provides @exceptionhandler exception enhancement annotations. If the program throws an exception before or during execution of the Controller method, it is handled by the @exceptionhandler annotated method.

Configuration applicationcontext-mvc.xml:

<!--use annotation to automatically register beans, scan @controller and @controlleradvice--><context:component-scan base-package= " Com.drskj.apiservice "use-default-filters=" false ">    <!--base-package If multiple, with", "separated--    <context: Include-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller"/>    <!--controller enhancements, To make a contoller a global exception-handling class, the method annotated by the @exceptionhandler method can handle the exception that occurs with all controllers-and    <context:include-filter type= "Annotation" expression= "Org.springframework.web.bind.annotation.ControllerAdvice"/></context: Component-scan>

Global Exception Handling classes:

Package Com.drskj.apiservice.handler;import Java.io.ioexception;import Org.springframework.beans.conversionnotsupportedexception;import Org.springframework.beans.typemismatchexception;import Org.springframework.http.converter.httpmessagenotreadableexception;import Org.springframework.http.converter.httpmessagenotwritableexception;import Org.springframework.web.httpmediatypenotacceptableexception;import Org.springframework.web.httprequestmethodnotsupportedexception;import Org.springframework.web.bind.missingservletrequestparameterexception;import Org.springframework.web.bind.annotation.controlleradvice;import Org.springframework.web.bind.annotation.exceptionhandler;import Org.springframework.web.bind.annotation.responsebody;import com.drskj.apiservice.common.utils.returnformat;/** * exception enhancement, returned to the customer service in JSON form
* Exception Enhancement Type: Nullpointerexception,runtimeexception,classcastexception,
Nosuchmethodexception,ioexception,indexoutofboundsexception
and SPRINGMVC custom exceptions, as follows:
SPRINGMVC a custom exception corresponding to the status code
           Exception HTTP Status Code conversionnotsupportedexception (Internal Server Error) httpmessagenotwritableexception (Internal Server error) httpmediatypenotsupportedexception 415 (Unsu pported Media Type) httpmediatypenotacceptableexception 406 (not acceptable) Httprequestmethodnotsupportedexception 40 5 (Method not allowed) Nosuchrequesthandlingmethodexception 404 (Not Found) Typemismatchexception 400 (Bad Request) Httpmessagenotreadableexception (Bad Request) missingservletrequestparameterexception (Bad Request) * */@Co Ntrolleradvicepublic class restexceptionhandler{//Run-time exception @ExceptionHandler (Runtimeexception.class) @ResponseBod Y public String Runtimeexceptionhandler (runtimeexception runtimeexception) {return Returnformat.retparam (10    XX, NULL); }//null pointer exception @ExceptionHandler (NULLPOINTEREXCEPTION.CLASS) @ResponseBody public String NullpointerexceptiOnhandler (NullPointerException ex) {ex.printstacktrace ();    Return Returnformat.retparam (1001, NULL); }//Type conversion exception @ExceptionHandler (classcastexception.class) @ResponseBody public String Classcastexceptionha        Ndler (ClassCastException ex) {ex.printstacktrace ();      Return Returnformat.retparam (1002, NULL);  }//io exception @ExceptionHandler (ioexception.class) @ResponseBody public String Ioexceptionhandler (IOException        Ex) {ex.printstacktrace ();     Return Returnformat.retparam (1003, NULL); }//Unknown method exception @ExceptionHandler (nosuchmethodexception.class) @ResponseBody public String nosuchmethodexcept        Ionhandler (Nosuchmethodexception ex) {ex.printstacktrace ();    Return Returnformat.retparam (1004, NULL); }//array out of Bounds exception @ExceptionHandler (indexoutofboundsexception.class) @ResponseBody public String Indexoutofboun Dsexceptionhandler (Indexoutofboundsexception ex) {ex.Printstacktrace ();    Return Returnformat.retparam (1005, NULL); }//400 Error @ExceptionHandler ({httpmessagenotreadableexception.class}) @ResponseBody public String Requestnotrea        Dable (Httpmessagenotreadableexception ex) {System.out.println ("400..requestNotReadable");        Ex.printstacktrace ();    Return Returnformat.retparam (n, NULL); }//400 Error @ExceptionHandler ({typemismatchexception.class}) @ResponseBody public String Requesttypemismatch (TYP        Emismatchexception ex) {System.out.println ("400..TypeMismatchException");        Ex.printstacktrace ();    Return Returnformat.retparam (n, NULL); }//400 Error @ExceptionHandler ({missingservletrequestparameterexception.class}) @ResponseBody public String Reque Stmissingservletrequest (Missingservletrequestparameterexception ex) {System.out.println ("400).        Missingservletrequest ");        Ex.printstacktrace ();    Return Returnformat.retparam (n, NULL); }//405 Error @ExCeptionhandler ({httprequestmethodnotsupportedexception.class}) @ResponseBody public String request405 () {Syst        Em.out.println ("405 ...");    Return Returnformat.retparam (405, NULL); }//406 Error @ExceptionHandler ({httpmediatypenotacceptableexception.class}) @ResponseBody public String REQUEST40        6 () {System.out.println ("404 ...");    Return Returnformat.retparam (406, NULL); }//500 Error @ExceptionHandler ({conversionnotsupportedexception.class,httpmessagenotwritableexception.class}) @Respo        Nsebody public String server500 (runtimeexception runtimeexception) {System.out.println ("500 ...");    Return Returnformat.retparam (406, NULL);  }}

The above includes common service-side exception types, @ResponseBody representing the return of client data in JSON format. We can also customize the exception class (Here I call it myexception) and inherit RuntimeException, and add a new method to handle the exception in the global exception handling class, using @exceptionhandler ( Myexception.class) Annotations Implement custom exception enhancements on methods.

Format response Data Class Returnformat:

Package Com.drskj.apiservice.common.utils;import Java.lang.reflect.field;import Java.text.simpledateformat;import Java.util.arraylist;import java.util.date;import java.util.hashmap;import Java.util.list;import java.util.Map; Import com.alibaba.fastjson.json;import com.google.common.collect.maps;//format return client data format (JSON) public class    Returnformat {private static Map<string,string>messagemap = Maps.newhashmap ();        Initialize the status code with literal description static {Messagemap.put ("0", "");        Messagemap.put ("n", "Bad request!");        Messagemap.put ("401", "Notauthorization");        Messagemap.put ("405", "Method not Allowed");        Messagemap.put ("406", "not acceptable");        Messagemap.put ("$", "Internal Server Error");        Messagemap.put ("1000", "[Server] Runtime exception");        Messagemap.put ("1001", "[Server] Null value exception");        Messagemap.put ("1002", "[Server] Data type conversion exception");        Messagemap.put ("1003", "[Server]io exception");        Messagemap.put ("1004", "[Server] Unknown method exception"); Messagemap.put ("1005", "[Server] array out of bounds exception");        Messagemap.put ("1006", "[Server] Network exception");        Messagemap.put ("1010", "User not registered");        Messagemap.put ("1011", "user registered");        Messagemap.put ("1012", "User name or password error");        Messagemap.put ("1013", "User account Freeze");        Messagemap.put ("1014", "User information editing failed");        Messagemap.put ("1015", "User information is invalid, please re-obtain");        Messagemap.put ("1020", "Verification code failed to send");        Messagemap.put ("1021", "Invalid verification Code");        Messagemap.put ("1022", "Captcha error");        Messagemap.put ("1023", "Verification Code not available");        Messagemap.put ("1029", "SMS Platform Anomaly");        Messagemap.put ("1030", "no shops around");        Messagemap.put ("1031", "Shop add Failed");        Messagemap.put ("1032", "Edit store information failed");        Messagemap.put ("1033", "each user can only add one shop");        Messagemap.put ("1034", "store does not exist");        Messagemap.put ("1040", "no browsing goods");        Messagemap.put ("1041", "Add failed, product category exceeds the limit");        Messagemap.put ("1042", "Commodity does not exist");        Messagemap.put ("1043", "Product deletion failed");                Messagemap.put ("2010", "Missing parameter or value is empty");        Messagemap.put ("2029", "parameter not valid"); Messagemap.put ("2020 "," Invalid token ");        Messagemap.put ("2021", "no Operation permission");        Messagemap.put ("2022", "RSA decryption failed, ciphertext data corrupted");    Messagemap.put ("2023", "Please login Again"); } public static String retparam (int status,object data) {Outputjson JSON = new Outputjson (Status, messagemap.ge        T (string.valueof (status)), data);    return json.tostring (); }}

Returns the format entity class Outputjson; Here's a well-known fastjson. Turn objects into JSON:

Package Com.drskj.apiservice.common.utils;import Java.io.serializable;import Com.alibaba.fastjson.json;public Class Outputjson implements serializable{/** * Returns the client unified format, including status code, prompt information, and business data */private static final long ser    Ialversionuid = 1L;    Status code private int status;    Necessary hint information private String message;    Business Data-private Object data;        Public Outputjson (int status,string message,object data) {this.status = status;        this.message = message;    This.data = data;    } public int GetStatus () {return status;    } public void SetStatus (int status) {this.status = status;    Public String GetMessage () {return message;    The public void Setmessage (String message) {this.message = message;    } public Object GetData () {return data;    } public void SetData (Object data) {this.data = data;    Public String toString () {if (null = = This.data) {this.setdata (New Object ());    } return json.tojsonstring (this); }}

Example: Codecontroller inherits from Basecontroller, there is a SendMessage method call service layer to send SMS verification code;

1. If the client request mode is not post, otherwise throws httpmediatypenotsupportedexception exception;

2. If username, fortype or usertype are not transmitted, the missingservletrequestparameterexception exception is thrown;

3. If SPRINGMVC receives a field that cannot be converted by type, it will report typemismatchexception exception;

.....

Most of the request is abnormal, SPRINGMVC has been defined for us, developed for our restful application to improve the efficiency of testing, to facilitate the troubleshooting of the link.

@RestController
@RequestMapping ("/api/v1/code")
public class Codecontroller extends Basecontroller {@Autowired private codeservice codeservice; /** * Send SMS * @param username username * @param type REGISTER/BACKPWD * @return * status:0 2010 2029 1011 1 010 1006 1020 * * @RequestMapping (value= "/sendmessage", method=requestmethod.post,produces= "Application/json") pu Blic string SendMessage (@RequestParam (value= "username", Required=true) string username, @RequestParam (value= "ForT Ype ", required=true) string fortype, @RequestParam (value=" usertype ", Required=true) string usertype) {if (nul L = = Username | |        ". Equals (username)) {return retcontent, null); } if (! " User ". Equals (usertype) &&!"        Merchant ". Equals (usertype)) {return retcontent (2029, NULL); } if (! " Register ". Equals (Fortype) &&!"        Backpwd ". Equals (Fortype)) {return retcontent (2029, NULL); } return Codeservice.sendmessage (username, fortype, usertype); }}
Public abstract class Basecontroller {    protected String retcontent (int status,object data) {        return Returnformat . Retparam (status, data);}    }

Eventually, the Returnformat.retparam (int status,objectdata) method is called toreturn the formatted uniform data, whether it is a normal business logic or a service-side exception.

SPRINGMVC return to client by exception enhancement uniform format

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.