spring mvc 輸出 json 異常日誌、異常國際化處理

異常日誌

 

上面一篇寫了異常處理,直接拋出,都交給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、異常、異常日誌、異常國際化等信息。

 

日後有改善再續

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章