Java Custom exception information

Source: Internet
Author: User

Usually in the development process, you will encounter a lot of exceptions, for some know the cause of the exception, when you want to return to the browser, you need to customize the system's exceptions

1. Spring Injection Exception Handling class

<= "Commonexceptionhandler"= "com. Test.common.exception.handler.CommonExceptionHandler ">

2, the injection of exception processing class, mainly is to rewrite the Resolveexception method

Import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Net.sf.json.jsonobject;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.web.servlet.handlerexceptionresolver;import Org.springframework.web.servlet.modelandview;import Com.test.common.constant.errorconstants;import Com.test.common.constant.globalconstants;import Com.test.common.dto.resultdto;import Com.test.common.exception.serviceexception;import Com.test.common.exception.sysexception;import Com.test.common.util.springcontextholder;import Com.test.common.util.stringutil;public Class Commonexceptionhandler implements Handlerexceptionresolver {private static final Logger LOG = Loggerfactory.getlogger (    Commonexceptionhandler.class);    /** * @param request parameter * @param response parameter * @param obj parameter * @param e parameter * @return Modelview * * Public Modelandview resolveexception (httpservLetrequest request, HttpServletResponse response, Object obj, Exception e) {resultdto result;        if (e instanceof sysexception) {result = Handlesysexception ((sysexception) e);        } else if (e instanceof serviceexception) {result = Handleserviceexception ((serviceexception) e);        } else {result = Handlesysexception (new Sysexception (Errorconstants.common_system_error, E));        } responseoutwithjson (response, result);    return new Modelandview (); }
Private Resultdto Handlesysexception (Sysexception ex) {resultdto result = new Resultdto (); Result.setcode (Ex.getcode ()); if (Stringutil.isnotempty (Ex.getmsg ())) {Result.setmessage (ex.getmsg ());//Get the information you set here}else {Resul T.setmessage (Springcontextholder.getmessage (Ex.getcode (), null));} Log.error (New StringBuilder (). Append (Result.getcode ()). Append (Result.getmessage ()). ToString (), ex); return result; } private Resultdto Handleserviceexception (Serviceexception ex) {resultdto result = new Resultdto (); Result.setcode (Ex.getcode ()); Result.setmessage (Springcontextholder.getmessage (Ex.getcode (), null)); Log.error (New StringBuilder (). Append (Result.getcode ()). Append (Result.getmessage ()). ToString ()); return result; } protected void Responseoutwithjson (httpservletresponse response, Object responseobject) {jsonobject Responsej Sonobject = Jsonobject.fromobject (responseobjecT); String jsonstring = responsejsonobject.tostring (); Response.setcharacterencoding (globalconstants.default_encoding); Response.setcontenttype ("Application/json; Charset=utf-8 "); PrintWriter out = null; try {out = Response.getwriter (); Out.append (jsonstring); Log.debug ("Return is \ n"); Log.debug (jsonstring); } catch (IOException e) {log.debug ("Error Responseoutwithjson"); } finally {if (out! = null) {out.close (); } } }}

3. Custom system Exception Class

 Packagecom.test.common.exception.base; Public classBasecommonexceptionextendsRuntimeException {Private Static Final LongSerialversionuid = 1L; PrivateString Code; PrivateString msg;//for storing exception information/*** Constructor Function*/     Publicbasecommonexception () {Super(); }    /**     *      * @paramcause Parameters*/     Publicbasecommonexception (Throwable cause) {Super(cause); }        /**     *      * @paramCode parameter*/     Publicbasecommonexception (String code) { This. Setcode (code); }    /**     *      * @paramCode parameter *@parame parameter*/     Publicbasecommonexception (String code, Throwable e) {Super(e);  This. Setcode (code); }        /**     *      * @paramCode parameter *@parame parameter*/     Publicbasecommonexception (String code, throwable e,string msg) {Super(e);  This. Setcode (code);  This. setmsg (msg); }    /**     *      * @returnCode*/     PublicString GetCode () {returnCode; }    /**     *      * @paramCode parameter*/     Public voidSetcode (String code) { This. Code =Code; }    /**     *      * @returnmsg*/     PublicString getmsg () {returnmsg; }    /**     *      * @parammsg Parameters*/     Public voidsetmsg (String msg) { This. msg =msg; }    }

4. Service class

     Public Boolean Test () {        = "";         Try {                        = "Custom Information";             return true ;         Catch (Exception e) {            thrownew  basecommonexception ("D", E,                    " Failure message: "+msg";        }    }    

Java Custom exception information

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.