In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "the method of Spring Boot unified interface return and global exception handling". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "Spring Boot unified interface return and global exception handling method".
1. Solution
Define common modules, achieve a unified interface definition specification and exception handling, other systems can rely on and expand.
2. Implement the unified interface public interface BaseResultCode {/ * status code * @ return * / int getCode (); / * prompt message * @ return * / String getMsg () Public module status code enumeration classes public enum ResultCode implements BaseResultCode {OK (200, "success"), ERROR (300, "system exception"), NEED_AUTH (301, "illegal request, please log in again"), PARAMTER_ERROR (302, "parameter error"); / / omitting other definition error codes private int code; private String msg Private ResultCode (int code, String msg) {this.code = code; this.msg = msg;} public static ResultCode getValue (int code) {for (ResultCode errorCode: values ()) {if (errorCode.getCode () = = code) {return errorCode;}} return null } / / omit Get, Set methods} 2.3 define global custom exception public class SysException extends RuntimeException {private static final long serialVersionUID = 5225171867523879342L; private int code; private String msg; private Object [] params; private BaseResultCode errorCode; public SysException () {super ();} public SysException (String message) {super (message) } public SysException (Throwable cause) {super (cause);} public SysException (int code, String message) {this.code = code; this.msg = message;} public SysException (int code, String message, Object [] params) {this (code, message); this.params= params;} public SysException (String message, Throwable cause) {super (message, cause) } public SysException (BaseResultCode errorCode) {this.errorCode = errorCode;} public SysException (String message, Object [] params) {super (message); this.params = params;} public SysException (BaseResultCode errorCode, String message, Object [] params) {this (message, params); this.errorCode = errorCode } / * Construct by default * * @ param message * message * @ param parameters * parameters * @ param cause * cause * / public SysException (String message, Object [] params, Throwable cause) {super (message, cause); this.params = params } public int getCode () {return code;} public void setCode (int code) {this.code = code;} public String getMsg () {return msg;} public void setMsg (String msg) {this.msg = msg;} / * @ return the params * / public Object [] getParams () {return params } / * * @ param params * the params to set * / public void setParams (Object [] params) {this.params = params;} public BaseResultCode getErrorCode () {return errorCode;} public void setErrorCode (BaseResultCode errorCode) {this.errorCode = errorCode Define unified interface format output class public class Result implements Serializable {private static final long serialVersionUID =-1773941471021475043L; private Object data; private int code; private String msg; public Result () {} public Result (int code, Object data, String msg) {this.code = code; this.data = data; this.msg = msg } public Result (int code, String desc) {this (code, null, desc);} public Result (BaseResultCode errorCode) {this (errorCode.getCode (), null, errorCode.getMsg ());} public static Result success () {return success (null);} public static Result success (Object data) {Result result = new Result (); result.setData (data) Result.setCode (ResultCode.OK.getCode ()); return result;} public static Result error (String msg) {Result result = new Result (); result.setCode (ResultCode.ERROR.getCode ()); result.setMsg (msg); return result;} public static Result error (BaseResultCode baseCode) {Result result = new Result (); result.setCode (baseCode.getCode ()) Result.setMsg (baseCode.getMsg ()); return result;}
Personal advice: unified interface output classes should not be defined as generic types
2.5 define the unified interface format output class @ RestControllerAdvicepublic class SysExceptionHandler {public static Log logger = LogManager.getLogger (SysExceptionHandler.class); @ ExceptionHandler (Exception.class) public Result handleException (HttpServletRequest request, Exception ex) {logger.error ("Handle Exception Request Url: {}, Exception: {}", request.getRequestURL (), ex); Result result = new Result () / / system exception if (ex instanceof SysException) {SysException se = (SysException) ex; BaseResultCode resultCode= se.getErrorCode (); if (resultCode==null) {result = Result.error (se.getMessage ()) } else {result = new Result (resultCode.getCode (), StringUtil.isNotEmpty (se.getMessage ())? se.getMessage (): resultCode.getMsg ()) }} / / Parameter error else if (ex instanceof ConstraintViolationException) {ConstraintViolationException v = (ConstraintViolationException) ex; String message = v.getConstraintViolations (). Iterator (). Next () .getMessage (); result.setCode (ResultCode.PARAMTER_ERROR.getCode ()) Result.setMsg (ResultCode.PARAMTER_ERROR.getMsg () + ":" + message);} / / Parameter error else if (ex instanceof BindException) {BindException v = (BindException) ex; String message = v.getAllErrors () .stream () .map (ObjectError::getDefaultMessage) .parameters (Collectors.joining (",")); result.setCode (ResultCode.PARAMTER_ERROR.getCode ()) Result.setMsg (ResultCode.PARAMTER_ERROR.getMsg () + ":" + message);} / / Parameter error else if (ex instanceof MethodArgumentNotValidException) {MethodArgumentNotValidException v = (MethodArgumentNotValidException) ex; String message = v.getBindingResult (). GetAllErrors (). Stream (). Map (ObjectError::getDefaultMessage) .parameters (Collectors.joining (",")) Result.setCode (ResultCode.PARAMTER_ERROR.getCode ()); result.setMsg (ResultCode.PARAMTER_ERROR.getMsg () + ":" + message);} else {result = new Result (ResultCode.ERROR.getCode (), ExceptionUtil.getErrorMsg (ex));} logger.info ("exception handle reuslt:" + result); return result;}}
The above definition has been able to achieve the unified handling of global interfaces and exceptions, but the following problems exist
Each controller needs to return a Reesult type, and each method needs to return the result of Result.success () or Result.success (data), which is a bit repetitive and needs to be optimized.
@ GetMapping ("addUser") public Result add () {for (int iTuno political I > selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {logger.info ("before body write param: {}", o); if (o instanceof String) {/ / serialize the result output return FastJsonUtil.toJSONString (Result.success (o)) } else if (o instanceof Result) {return o;} return Result.success (o);}}
After optimization, the controller output can be defined according to the needs of the business.
@ GetMapping ("getUserByName") public TUser getUserByName1 (@ RequestParam String name) {logger.info ("getUserByName paramter name:" + name); return userService.getUserByName (name);} 2.7 how to implement the subsystem
The subsystem introduces the jar package of common
Com.xx xx-common 2.03. The subsystem defines the status code and implements BaseResultCode interface public enum OrderModelErrorCode implements BaseResultCode {ORDER_STATUS_ERROR (1000, "incorrect order status"); private int code; private String msg; private UserModelErrorCode (int code, String msg) {this.code = code; this.msg = msg } @ Override public int getCode () {return code;} @ Override public String getMsg () {return msg;}}
Define exception handling class and inherit common exception handling class SysExceptionHandler
@ RestControllerAdvicepublic class OrderModalExceptionHandle extends SysExceptionHandler {@ Override public Result handleException (HttpServletRequest request, Exception ex) {return super.handleException (request, ex); / / the subsystem can extend exception handling}}
Examples of subsystem usage:
@ Overridepublic Order getOrder (String orderId) {Order order = getOrder (orderId); / / related pseudo code if (order.getStatus () > 120) {throw new SysException (OrderModelErrorCode.ORDER_STATUS_ERROR);} return order } Thank you for your reading. the above is the content of "Spring Boot unified interface return and global exception handling methods". After the study of this article, I believe you have a deeper understanding of the Spring Boot unified interface return and global exception handling methods, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.