springboot was used in the project, which was very happy, but there was nothing in the project, validation, global exceptions needed to be configurated in their own area. springboot has been using a lot lately. I'll do something to publish my experience. Global unified exceptions, first of all, the return value of exceptions and the return value of normal returns should be unified json. The code and msg of return value can be saved by enum, and the method of controller layer throws exceptions. See the code below.
package com.imooc.shoptest001.handle; import com.imooc.shoptest001.utils.JsonData; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * Global exception capture */ @ControllerAdvice public class ExceptionHandle { /** * ExceptionHandler What exception is caught * ResponseBody Return to json format * @return */ @ExceptionHandler(value = Exception.class) @ResponseBody public JsonData handle(Exception ex){ ex.printStackTrace(); System.out.println(ex.toString()); return JsonData.error500(ex.getMessage()); } }
package com.imooc.shoptest001.utils; public enum JsonDataEnum { ERROR(-1,"fail"), SUCCESS(0,"Success"), ; private Integer code; private String msg; JsonDataEnum(Integer code,String msg){ this.code = code; this.msg = msg; } public Integer getCode() { return code; } public String getMsg() { return msg; } }
package com.imooc.shoptest001.utils; /** * Front desk returns json class */ public class JsonData<T> { /** * Return state */ private boolean status; /** * Error code/correct code */ private Integer code; /** * News. */ private String msg; /** * Specific content. */ private T data; public static JsonData success(String msg,Object data){ JsonData jsonData = new JsonData(); jsonData.setMsg(msg); jsonData.setStatus(true); jsonData.setCode(200); jsonData.setData(data); return jsonData; } public static JsonData ok(){ JsonData jsonData = new JsonData(); jsonData.setStatus(true); jsonData.setCode(200); return jsonData; } public static JsonData error(Integer code,String msg){ JsonData jsonData = new JsonData(); jsonData.setStatus(false); jsonData.setCode(code); jsonData.setMsg(msg); return jsonData; } public static JsonData error500(String msg){ JsonData jsonData = new JsonData(); jsonData.setStatus(false); jsonData.setCode(500); jsonData.setMsg(msg); return jsonData; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } 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; } }