preface

Those who have used the Spring family bucket should know that the exception handling of business logic in most systems is intercepted and packaged by the unified exception processor based on SpringMVC, and a Result object (including code, MSG and other messages of business exception) is returned to the front end. The front end can provide friendly prompt according to code and MSG. As follows:

  1. Custom business logic exceptions
/** * @author meilin. Huang * @version 1.0 * @date 2019-01-05 2:19pm */ public class BusinessRuntimeException extends RuntimeException { private static final long serialVersionUID = -789021883759549647L; /** * exception code */ private Integer code; public BusinessRuntimeException(String msg) { super(msg); } public BusinessRuntimeException(Integer code, String msg) { super(msg); this.code = code; } public IntegergetCode() {
        returncode; }}Copy the code
  1. Define a unified exception interceptor
/**
 * @author meilin.huang
 * @version 1.0
 * @date 2018-12-18 11:03 AM
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        if (e instanceof BusinessException || e instanceof BusinessRuntimeException) {
            return Result.error(e.getMessage());
        }
        returnResult.serverError(); }}Copy the code
  1. You can throw custom business logic exceptions in your business logic at will
public void updateUser(UserForm userForm) {
  User user = getById(userForm.getId);
  if (user == null) {
    throw new BusinessRuntimeException("The user does not exist"); } // Verify the existence of the user state enumeration. This can also be verified at the Controller layer via annotations, for exampleif(! EnumUtils.isExist(StatusEnum.values(), userForm.getStatus())) { throw new BusinessRuntimeException("Status enumeration value error"); } / /... // There may be some other business logic check and throw exception code left}Copy the code

A more elegant solution

It can be found from the above business judgment that the judgment processing of these business logic is basically based on if(…). {throw new BusinessRuntimeException(…) } so it can be drawn lessons from the Spring org. Springframework. Util. The Assert class for processing, can reduce a lot of the if of judgment. Please refer to the following for details:

  1. Start by defining a business assertion class
@author meilin. Huang * @version 1.0 * @date 2019-07-14 18:24 */ public Final Class BusinessAssert {/** * Public static void notNull(object object, param MSG) String msg) { state(object ! = null, msg); } public static void notNull(Object object, Supplier<String> supplier) { state(object ! = null, supplier); } public static void notEmpty(String String, String String, String String, String String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String) String msg) { state(! StringUtils.isEmpty(str), msg); } public static void notEmpty(collection <?) public static void notEmpty(collection <? > collection, String msg) { state(! CollectionUtils.isEmpty(collection), msg); } /** * declare a Boolean expression * @param expression Boolean expression * @param message does not satisfy the asserted exception information */ public static void state(Boolean) expression, String message) {if(! expression) { throw new BusinessRuntimeException(message); }} /** * a Boolean expression, @param expression Boolean expression @param supplier MSG producer */ public static void state(Boolean expression, Supplier<String> supplier) {if(! expression) { throw new BusinessRuntimeException(supplier.get()); }}}Copy the code
  1. This can then be used in business logic code as follows:
public void updateUser(UserForm userForm) {
  User user = getById(userForm.getId);
  BusinessAssert.notNull(user, "The user does not exist"); // Check the existence of the user state enumeration. This can also be checked at the Controller layer via annotations. Businessassert.state (Enumutils.isexist (StatusEnum. Values (), userForm.getStatus())),"Status enumeration value error"); / /... // There may be some other business logic check and throw exception code left}Copy the code

conclusion

The use of assertions based on business logic judgment, obviously more elegant and concise than the first way, can also write a lot of code, you can try to use to see the clasp, comfortable is not a little bit.