1. newly build GlobalExceptionHandler Global exception handling class

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * handle MyException abnormal
     */
    @ExceptionHandler(MyException.class)
    public ReturnJson<Object> myExceptionHandler(MyException ex) {
        return new ReturnJson<Object>(ResultStatusEnum.FAILURE.getCode(),
ResultStatusEnum.FAILURE.getMessage(), null);
    }
    
    /**
     * handle RunTimeException abnormal
     */
    @ExceptionHandler(RuntimeException.class)
    public ReturnJson<Object> runtimeExceptionHandler(RuntimeException ex) {
        return new ReturnJson<Object>(ResultStatusEnum.FAILURE.getCode(),
ResultStatusEnum.FAILURE.getMessage(), null);
    }
}
 

2. Custom exception class MyException inherit RuntimeException

@Getter
public class MyException extends RuntimeException{
    /*
     * Status code
     */
    private int code;
    /*
     * Message prompt
     */
    private String message;
    
    public MyException(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public MyException(ResultStatusEnum resultStatusEnum) {
        this.code = resultStatusEnum.getCode();
        this.message = resultStatusEnum.getMessage();
    }

}
 

3. Other classes used

@Data
public class ReturnJson<T> {
    /*
     * Status code
     */
    private int code;
    /*
     * Message prompt
     */
    private String message;
    /*
     * Return content
     */
    private T info;
    
    public ReturnJson(int code,String message ,T info) {
        this.code=code;
        this.message=message;
        this.info=info;
    }
}

 

@NoArgsConstructor
@AllArgsConstructor
public enum ResultStatusEnum {
    /**
     * Request succeeded
     */
    SUCCESS(200, " Request succeeded !"),
    
    /*
     * request was aborted
     */
    FAILURE(400, " request was aborted !");
    
    @Getter
    @Setter
    private int code;
    
    @Getter
    @Setter
    private String message;
}

Technology
©2019-2020 Toolsou All rights reserved,
JAVA Detailed explanation of anomalies MySQL An interview is a must ! How to use it quickly html and css Write static page R Language cluster analysis case Dialogue between apple and Nissan suspended ,Apple Car How's it going ?java Realize the function of grabbing red packets SpringBoot practice ( five ):mybatis-plus In BaseMapper,Iservice and ServiceImpl Google says home office affects work efficiency !2021 Return to offline office in 2010 about keras use fit_generator Encountered in StopIteration Programmer Tanabata Valentine's Day confession code