springboot 統一異常類
阿新 • • 發佈:2020-07-15
我這裡是統一返回json格式的
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = GovCommException.class) @ResponseBody public Result jsonErrorHandler(HttpServletRequest req, GovCommException e) throws Exception{ Result res = new Result(); res.setCode(Result.ERROR_CODE); res.setMsg("請求url:"+req.getRequestURI().toString()+",錯誤資訊:"+e.getMessage()); return res; } }
異常類
public class GovCommException extends Exception{ public GovCommException(){ super(); } public GovCommException(String msg){ super(msg); } public GovCommException(String msg, Throwable e){super(msg,e); } }
DTOResult
public class Result<T> implements Serializable { public static final int SUCCESS_CODE = 200; public static final int ERROR_CODE = 100; private static final long serialVersionUID = 1L; private static final String SUCCESS = "操作成功。"; private staticfinal String ERROR = "操作失敗!!!"; private Integer code; private String msg; @JsonInclude(JsonInclude.Include.NON_NULL) private T data; @JsonInclude(JsonInclude.Include.NON_NULL) private Map<String,Object> ext; @JsonInclude(JsonInclude.Include.NON_NULL) private PageParam pageParam; public Result() { } public Result(Integer code, String msg) { this.code = code; this.msg = msg; } public Result(Integer code) { this.code = code; if (code==SUCCESS_CODE){ this.msg = SUCCESS; }else{ this.msg = ERROR; } } public Result(Integer code, String msg, T data) { this.code = code; this.msg = msg; this.data = data; } public Result(Integer code, String msg, T data, Map<String, Object> ext) { this.code = code; this.msg = msg; this.data = data; this.ext = ext; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; if (code==Result.SUCCESS_CODE){ this.msg = SUCCESS; }else { this.msg = ERROR; } } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Map<String, Object> getExt() { return ext; } public void setExt(Map<String, Object> ext) { this.ext = ext; } public PageParam getPageParam() { return pageParam; } public void setPageParam(PageParam pageParam) { this.pageParam = pageParam; } }
異常使用
@GetMapping("/notifyAll") public Result loaderAll() throws GovCommException { Result res = new Result(); try { Result result = ServerUtil.getModelManagerProxy(type).loaderAll(); if (result!=null) res = result; return res; } catch (Exception e) { throw new GovCommException("遠端通知服務端載入模型異常!",e); } }