java自定义异常并处理异常
生活随笔
收集整理的這篇文章主要介紹了
java自定义异常并处理异常
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
自定義異常:
/*** 自定義異常** @author ruoyi*/ @Data public final class MyException extends RuntimeException {private Integer status = ExceptionCode.SERVICEEXCEPTION.getCode();public MyException() {}public MyException(ExceptionCode status,String message) {super(status.getCode()+"&"+message);this.status = status.getCode();}public MyException(Throwable cause) {super(cause);}public MyException(String message, Throwable cause) {super(message, cause);}public MyException(String message, Throwable cause,boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}} /*** 自定義異常狀態* * @author ruoyi*/ public enum ExceptionCode {TOKENEXCEPTION(40000),//登錄TOKEN異常SERVICEEXCEPTION(41000),//業務異常(包括參數)AUTHEXCEPTION(42000);//權限異常private final Integer code;ExceptionCode(Integer code){this.code = code;}public Integer getCode(){return code;}}自定義異常處理:
/*** 自定義異常處理*/ @ControllerAdvice @Slf4j public class MyExceptionHandler {@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)public void handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) {//返回給前端的信息Map<String, Object> map = new HashMap<String, Object>();String message = ex.getMessage();Integer status = 500;if(ex.getClass().equals(MyException.class)){//是自定義異常String[] str = message.split("&");status = MyUtil.convertToInt(str[0], 500);message = str[1];}else{message = "系統錯誤";}if (status.equals(500)) {System.out.println("非業務異常,請查看錯誤日志");log.error(MyExceptionUtil.getExceptionAllinformation(ex));} else {System.out.println("錯誤" + status + ":" + message);}map.put("status", status);map.put("message", message);request.setAttribute("errorMap", map);response.setHeader("Content-Type", "application/json");response.setStatus(403);MyUtil.writeObjectToClient(map, response);} } /*** 異步傳輸Json數據** @param obj* @param response* @throws JsonGenerationException* @throws JsonMappingException* @throws IOException* @author wzd* @description* @date 2013-2-28*/public static void writeObjectToClient(Object obj, HttpServletResponse response) {String jsonStr = JSON.toJSONString(obj);response.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");try {response.getWriter().print(jsonStr);} catch (IOException e) {e.printStackTrace();}}/*** 獲得異常的字符串形式信息* @param e 要打印的異常* @return*/public static String getExceptionAllinformation(Exception e) {ByteArrayOutputStream out = new ByteArrayOutputStream();PrintStream pout = new PrintStream(out);e.printStackTrace(pout);String ret = new String(out.toByteArray());pout.close();try {out.close();} catch (Exception e1) {e1.printStackTrace();}return ret;}結束:
這樣只要
throw new MyException(ExceptionCode.SERVICEEXCEPTION,"");就能返回異常信息給前端了,前端就能統一進行異常處理了。
總結
以上是生活随笔為你收集整理的java自定义异常并处理异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蜘蛛图表SpiderChart
- 下一篇: 蓝牙防丢器距离的计算