spring mvc 输出 json 异常日志、异常国际化处理

4 篇文章 0 订阅
3 篇文章 0 订阅

异常日志

 

上面一篇写了异常处理,直接抛出,都交给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、异常、异常日志、异常国际化等信息。

 

日后有改善再续

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值