赞
踩
异常日志
上面一篇写了异常处理,直接抛出,都交给ExceptionResolver去处理,那么我们怎么记录日志呢?
因为异常直接抛出,使用拦截器即可。
异常国际化
我们可以设计一个异常类,异常类需要可以设置errorCode,以便将来支持国际化,系统中抛出的异常都是此异常或其子类。
例如BPLException,见附件
------------------spring mvc 配置---------------------------------
<!-- 使用cookie处理国际化-->
<bean id="localeResolver"class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName"value="clientLanguage" />
<property name="cookieMaxAge"value="-1" />
</bean>
<!-- 绑定国际化资源 -->
<bean id="messageSource"class="org.springframework.context.support.ResourceBundleMessageSource">
<propertyname="basenames">
<list>
<value>messages.demo</value>
</list>
</property>
</bean>
--------------------BaseController代码,基于上一篇-------------------------
private MessageSource messageSource;
public voidsetMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
/**
* 异常控制
* */
@ExceptionHandler(Exception.class)
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndViewhandleException(Exception ex, HttpServletRequest request) {
return new ModelAndView().addObject("error",getExceptionMessage(ex, request));
}
/**
* 获取异常的国际化信息,需要传递request对象(当然也可以使用ThreadLocal绑定request)。
* */
protected StringgetExceptionMessage(Exception ex, HttpServletRequest request) {
if(ex instanceof BPLException){
BPLException e = (BPLException) ex;
String[] errorCodes = e.getErrorCode();
if(errorCodes == null || errorCodes.length== 0){
return e.getMessage();
}else{
StringBuilder msg = new StringBuilder();
Locale locale =RequestContextUtils.getLocale(request);
for(String code : errorCodes){
msg.append(messageSource.getMessage(code,null, e.getMessage(), locale));
msg.append(',');
}
msg.deleteCharAt(msg.length()-1);
return msg.toString();
}
}else if(ex instanceofIllegalHrmPrivilegeException){
IllegalHrmPrivilegeException e =(IllegalHrmPrivilegeException) ex;
String[] codes = e.getCodes();
StringBuilder msg = new StringBuilder("缺少权限:");
if(codes != null && codes.length !=0){
msg.append('[');
for(String code : codes){
msg.append(code);
msg.append(',');
}
msg.deleteCharAt(msg.length()-1);
msg.append("]");
}
return msg.toString();
}else{
return "系统未知错误,请联系信息部!";
}
}
dao、manager、service、controller层不必处理异常,没必要写try...catch,又在catch中抛出。
除非有必要才在controller中手动处理。
到此,系统中可以自动处理JSON、异常、异常日志、异常国际化等信息。
日后有改善再续
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。