Project summary (second, uniform exception handling)

Source: Internet
Author: User

Second, unified exception handling

We know that if a project is layered, the exception needs to be thrown up a layer to the action layer, and then the action handles the exception, prompting friendly exception information to the user. If you use Try{}catch in every method of the action, there are a lot of similar code, and if you need to add some logic to exception handling, there are a lot of things that need to be changed, too much work and not easy to maintain. The project intends to use Struts's interceptor mechanism to achieve uniform exception handling.

1. Struts configuration file

First, customize the interceptor stack, configured as follows:

<!--Custom Interceptor stacks--

<interceptors>

<interceptor name= "defaultexceptioninterceptor" class= "xxx. Defaultexceptioninterceptor "/>

<interceptor-stack name= "Systemdefaultstack" >

<interceptor-ref name= "Defaultstack"/>

<interceptor-ref name= "Defaultexceptioninterceptor"/>

</interceptor-stack>

</interceptors>

<!--reference the default interceptor stack--

<default-interceptor-ref name= "systemdefaultstack"/>

2. Custom enumeration Class (added in the method that needs to be intercepted)

@Target (Elementtype.method)

@Retention (Retentionpolicy.runtime)

Public @interface Exceptionmeta {

public eoperstatus resultcode () default eoperstatus.failure;

public String message ();

}

3. Interceptor Class (temporarily processing only AJAX requests)

public class Defaultexceptioninterceptor extends Abstractinterceptor {

private static final long serialversionuid = -1409945647583201366l;

Private final static Logger Logger = Logger.getlogger (Defaultexceptioninterceptor.class);

@Override

public String intercept (actioninvocation invocation) throws Exception {

String result = "";

try {

result = Invocation.invoke ();

} catch (Exception e) {

Logger.error (E.getmessage (), E);

//exception handling

Actioncontext actioncontext = Invocation.getinvocationcontext ();

HttpServletRequest request = (httpservletrequest) actioncontext.get (strutsstatics.http_request);

Determine if it is an AJAX request

if (this.isajaxrequest (request)) {

//GET Request action Class

class<?> clazz = Invocation.getaction (). GetClass ();

//Get the method name corresponding to the request action

String methodName = Invocation.getproxy (). GetMethod ();

//Find out if the exception object already exists in the cache, if present, return directly, otherwise the exception object is added to the cache

Exceptionmeta Exceptionmeta = this.putifabsent (Clazz, methodName);

if (Exceptionmeta! = null) {

//Add exception error code and exception message to map

map<string, object> operatemap = new hashmap<string, object> (2);

operatemap.put ("ResultCode", Exceptionmeta.resultcode (). ID ());

operatemap.put ("message", Exceptionmeta.message ());

//Put the map into the value stack and return the map data to the foreground in JSON format in XML

Valuestack stack = Invocation.getstack ();

stack.set ("Operatemap", Operatemap);

}

result = "Ajaxexception";

}

}

return result;

}

/**

* Determine if there is a Exceptionmeta object for the specified key in the cache, and if so, remove the data from the cache, otherwise add the Exceptionmeta object to the cache

* @param the class of Clazz action

* @param methodName action corresponding to the method name

* @return Exceptionmeta

* @throws Exception exception

*/

Private Exceptionmeta putifabsent (class<?> clazz, String methodName) {

try {

String exceptionkey = clazz.getname () + "." + MethodName;

Exceptionmeta Exceptionmeta = Exceptioncache.get (Exceptionkey);

if (Exceptionmeta = = null) {

method = Clazz.getmethod (MethodName);

if (Method! = null) {

Exceptionmeta = method.getannotation (Exceptionmeta.class);

exceptioncache.put (Exceptionkey, Exceptionmeta);

}

}

return Exceptionmeta;

} catch (Exception e) {}

return null;

}

/**

* Determine if the request is an AJAX request

* @param request HttpServletRequest

* @return True or False

*/

Private Boolean isajaxrequest (HttpServletRequest request) {

String Header = Request.getheader ("X-requested-with");

if (header = null && "XMLHttpRequest". Equals (header)) {

return true;

}

return false;

}

}

4. Action method

@ExceptionMeta (ResultCode = eoperstatus.failure, message = "xxx")

Public String Post () throws Exception {

。。。

}

Where ResultCode represents the error code, message is a custom error message that is used to prompt the user.

Project summary (second, uniform exception handling)

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.