Jersey Rest exception Unification processing mechanism

Source: Internet
Author: User
Tags constant definition key string log log

Objective:

exceptions are run-time exceptions and non-runtime exceptions, so-called run-time exceptions are those that do not require exception captures, and are always taken over by virtual machines, such as: arrayindexoutofboundsexception, when we write programs, we do not use try. catch to catch it.

Previously, when we were developing projects, we habitually liked to use a lot of try...catch...finally methods for exception handling, and just saved the exception information in the log log, and did not return some of the exception information to the front-end users in a readable manner. In some larger projects, exception handling is one of the issues that architects or project managers must consider.

Jersey provides a unified exception handling mechanism that automatically jumps to the appropriate exception handling resource when a run-time exception occurs, and returns the processing results to the front-end user. For program developers, there is no need to write too many try...catch blocks, just use the throw keyword to throw a custom exception.

A unified mechanism of Jersey exception handling

1. Demonstration project structure and technology

(1) Technology: Spring4.1.4+jersey2.21+jpa+postman, using spring Data JPA technology, where PostMan is a test tool that can be installed in the Chrome browser, simulating the front-end sending requests to the server.

(2) Demonstration case construction using MAVEN

(3) The case structure is as follows:

(4) Case exception handling structure diagram

2, Business Scenario Description

In this project, justPage page number in a paged query cannot be negativeAs an example, the unified exception handling mechanism for jersey is demonstrated. When page page number is negative, throw userexception run-time exception, by jersey uniform exception Handling resource Class Exceptionmappingresource processing, the class resolves thrown exception information, Resolves the constant key defined by Exceptionkeys, reads the Chinese exception Unicode code defined by the configuration file Messages_zh_cn.properties, and can implement the parameter configuration.

3. Code Snippet Description

A, messages_zh_cn.properties exception configuration content

11110=\u67e5\u8be2\u8bf7\u6c42\u8d77\u59cb\u9875 {0} \u662f\u8d1f\u6570
where {0} indicates that a parameter value needs to be passed to assign a value, "11110" is key, and the Unicode code following the equals sign is the Chinese exception prompt that is returned to the front-end user

B, Exceptionkeys exception key constant definition content

Package Com.spring.jersy.jpa.hibernate.constants;public class Exceptionkeys {//All exception key strings are preceded by an E-ID, In the subsequent parsing process will intercept the E character, take the number after the E character//as follows: "E11110", become "11110" in order to correspond with the Messages_zh_cn.properties key one by one public final static String Page_number_greater_zero = "E11110";}

C, Messageutil exception Information parsing tool class

Package Com.spring.jersy.jpa.hibernate.util;import Java.text.messageformat;import Java.util.propertyresourcebundle;import Java.util.resourcebundle;import Com.spring.jersy.jpa.hibernate.exception.baseexception;public Final class Messageutil {private static Messageutil Instance = new Messageutil ();//For reading resource properties file (property) Private ResourceBundle Resourceboudle = null;public static Messageutil getinstance () {return instance;} /** * Gets the corresponding exception information according to the exception key * * @param Exceptionid * @return */public string getMessage (String exceptionid) {String message = Resourceboudle.getstring (Geterrorid (Exceptionid)); return message;} /** * Get the corresponding Chinese exception according to the exception * * @param e * @return */public string getMessage (Baseexception e) {String message = resourceboudle.g Etstring (Geterrorid (E.getmessage ())); object[] arguments = E.getvalues (); if (arguments! = null) {message = Messageformat.format (message, arguments);} return message;} Private Messageutil () {init ();} /** * Read, load storage key/value form, and Unicode encoded properties configuration information */private void INIT () {try {resourceboudle = new propertyResourceBundle (GetClass (). getClassLoader (). getResourceAsStream ("com/spring/ Jersy/jpa/hibernate/message/messages_zh_cn.properties "));} catch (Exception ex) {//Logger.error ("Error loading messages Properties", ex);}} /** * Intercept the exception number corresponding to the configuration file according to the exception number e11110--> becomes 11110 * * @param exceptionid *: Example Number E11110 * @return: Becomes 111 Ten */private string Geterrorid (String exceptionid) {Exceptionid = exceptionid.substring (1); return Exceptionid;}}
Among them, use Java.util. ResourceBundleclass to read, parse properties files, and use Java.text. Messageformatclass to format the message, and the {0} parameter in the configuration file is automatically replaced with the passed value.

D, Baseexception exception base class, Inherit RuntimeException

Package Com.spring.jersy.jpa.hibernate.exception;public class Baseexception extends RuntimeException {/** * */private Static final Long Serialversionuid = 1l;private object[] values;private int code = 500;public Baseexception () {}public Bas Eexception (String msg) {super (msg);}  Public baseexception (String msg, string ... params) {super (MSG); if (null! = params) {values = new object[params.length];for (int i = 0; i < params.length; i++) {Values[i] = params[i];}}} Public baseexception (string msg, int code, string ... params) {This (msg, params); this.code = code;} Public baseexception (String msg, int code) {super (msg); this.code = code;}  Public baseexception (String message, Throwable cause, string ... params) {super (message, cause); if (null! = params) {values = new Object[params.length];for (int i = 0; i < params.length; i++) {values[i] = params[i];}} public baseexception (int code, String message, Throwable cause,string ... params) {This (message, cause, params); This.code = code;} Public object[] GetValues () {return values;} public void Setvalues (object[] values) {this.values = values;} public int GetCode () {return code;} public void Setcode (int code) {this.code = code;}}
E, user exception handling class Userexception
Package Com.spring.jersy.jpa.hibernate.exception;import Com.spring.jersy.jpa.hibernate.constants.ExceptionKeys; public class Userexception extends baseexception{/** *  */private static final long serialversionuid = 1l;public Userex Ception () {}public userexception (String ... params) {super (exceptionkeys.page_number_greater_zero,params);}}
F, exception Unified processing class Exceptionmappingresource

Package Com.spring.jersy.jpa.hibernate.resource;import Javax.ws.rs.core.response;import Javax.ws.rs.core.response.responsebuilder;import Javax.ws.rs.ext.exceptionmapper;import Javax.ws.rs.ext.Provider ; Import Com.spring.jersy.jpa.hibernate.bean.exceptionresponse;import Com.spring.jersy.jpa.hibernate.exception.baseexception;import com.spring.jersy.jpa.hibernate.util.messageutil;/ * * This annotation must be added so that when a run-time exception occurs anywhere in the program, the exception is automatically handled uniformly * and the class is capable of being scanned by jersey to */@Providerpublic class Exceptionmappingresource Implements exceptionmapper<exception> {@Overridepublic Response toresponse (Exception Exception) { Responsebuilder Responsebuilder = null;//user-defined run-time exception handling if (Exception instanceof Baseexception) {//Get exception information thrown by user string Code = exception.getmessage ();//Gets the corresponding Chinese exception information according to the exception key string message = Messageutil.getinstance (). GetMessage (( baseexception) exception); Throwable cause = Exception.getcause (); if (cause! = null) {String Realreason = cause.getmessage (); message + = "possible cause:" + Realreason + "";} Custom exception returns entity Bean Class excEptionresponse error = new Exceptionresponse (); Error.setcode (code); error.setmessage (message); Error.setstatus (" Error ") Responsebuilder = Response.ok (Error). Status ((((baseexception) exception). GetCode ());} Other exception else {exceptionresponse error = new Exceptionresponse (); Error.setcode ("E000000"); Error.setmessage ( Exception.getmessage ()); Error.setstatus ("error"); Responsebuilder = Response.ok (Error). Status ( Response.Status.INTERNAL_SERVER_ERROR);} return Responsebuilder.build ();}}
Note:The class must be @ProviderAnd to implement the jax-rs provided by the ExceptionmapperIn order to keep track of the run-time exceptions thrown in the project, the class needs to be placed in a package that can be scanned by the JPA scanner.
G, User resource class Userresource test method of paging query

Paged Query @get@path ("/findbypage") @Produces (Mediatype.application_json) @Consumes (Mediatype.application_json) public Response Findbypage (@DefaultValue ("0") @QueryParam (value = "page") Integer page, @DefaultValue ("Ten") @QueryParam (value = "PageSize") Integer pageSize) {if (page >= 0) {list<user> listuser = Userspringdatajpaservice.finduserbypage (P Age,pagesize); Responsebuilder RB = null;if (Listuser = = null) {RB = Response.servererror (). status ($);} else {RB = Response.ok (listuser ). status (200);} return Rb.build ();} else {//If the page is negative, throw the exception throw new Userexception (page.tostring ());}}

Where the "page.tostring" parameter value is used to assign a value to the {0} parameter in Messages_zh_cn.properties, indicating that the value is negative.

Second, postman test

Postman is a good analog front-end sending request, testing the backend Code correctness test tool, can be installed via Chrome browser plugin, the interface is as follows:


Next, we are ready to test whether the Jersey Rest Unified Exception handling mechanism is successful and sends the following request connection:



Report:

Test Source: Spring Data jpa+jersey+testng User crud operation case

Jersey Rest exception Unification processing mechanism

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.