不同於傳統集中時Springmvc 全局異常,具體查看前面的章節https://www.cnblogs.com/zwdx/p/8963311.html 對於springboot框架來講,這裡我就介紹一種 1、ExceptionHandlerAdvice 由於是前後端分離,所以使用@ResponseB ...
不同於傳統集中時Springmvc 全局異常,具體查看前面的章節https://www.cnblogs.com/zwdx/p/8963311.html
對於springboot框架來講,這裡我就介紹一種
1、ExceptionHandlerAdvice
import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * 處理異常信息 * @author wdh * */ @ControllerAdvice @ResponseBody public class ExceptionHandlerAdvice extends MyExecptionHandler{ @ExceptionHandler(Exception.class) public ResultDTO handleException(Exception e,HttpServletResponse response) { return handler(e, response); } }
由於是前後端分離,所以使用@ResponseBody返回json
2、MyExecptionHandler
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject; /** * 自定義異常處理 * @author wdh * */ public class MyExecptionHandler{ public ResultDTO handler(Exception e,HttpServletResponse response){ 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 result; } private ResultDTO handleSysException(SysException ex) { ResultDTO result = new ResultDTO(); result.setCode(ex.getCode()); if(StringUtil.isNotEmpty(ex.getMsg())){ result.setMessage(ex.getMsg()); }else { result.setMessage(MessageEnums.fromcode(ex.getCode())); } return result; } private ResultDTO handleServiceException(ServiceException ex) { ResultDTO result = new ResultDTO(); result.setCode(ex.getCode()); result.setMessage(MessageEnums.fromcode(ex.getCode())); return result; } protected void responseOutWithJson(HttpServletResponse response, Object responseObject) { JSONObject responseJSONObject = JSONObject.fromObject(responseObject); String jsonString = responseJSONObject.toString(); String code = responseJSONObject.getString("code"); if (ERRORConstants.COMMON_EXCEL_FORMAT_ERROR.equals(code)) { response.setContentType("text/html;charset=UTF-8"); } else { response.setContentType("application/json; charset=utf-8"); } response.setCharacterEncoding(GlobalConstants.DEFAULT_ENCODING); PrintWriter out = null; try { out = response.getWriter(); out.append(jsonString); } catch (IOException e) { } finally { if (out != null) { out.close(); } } } }
其中異常代碼 ,為自己定義的GlobalConstants,MessageEnums