java Exception Handling Interceptor Details

  • 2021-12-04 09:59:08
  • OfStack

With exception handling interceptors, you don't have to write so much try…catch…。

I have a function, that is, the front-end submits short message content to the back-end, and the back-end carries out 1 series of processing, in which the short message content is submitted to the public short message interface. Micro-service framework and public SMS interface are another service. This will have a hidden danger, if this service does not open, or because of network reasons can not be accessed, how to do?

You can do atomic operations, you can resubmit things, and no matter what, you can't avoid error prompts. The problem is that the system is extremely unfriendly in the way of error prompt with naked code. This error should be caught and prompted with friendly content instead.

The most primitive method can be layer by layer try…catch…, From service 1 until controller Here it goes back to the front end. But it's too cumbersome and feels very low . As a programmer, you shouldn't be so mechanical.

Refer to the online method, in controller Set up an exception handling interceptor here:


@RestController
@RequestMapping("sms/order")
public class DzSmsSendOrderController {
 
  . . . 
 
    @ExceptionHandler(value = {
 RuntimeException.class})
    public ResultBody handleRuntimeException(Exception ex) throws Exception {
 
        if (ex.getMessage().indexOf("project-sms-api") != -1) {
 // Identification 1 Is the target exception under 
            return ResultBody.failed().msg(" Failed to access SMS interface, please confirm whether the related service is started ");
        } else throw ex;
    }
}

This ResultBody Is a custom object, and the front end judges whether it is successful according to the number returned by it.


@ApiModel(value = " Response result ")
public class ResultBody<T> implements Serializable {
 
  . . . 
 
    public static ResultBody failed() {
 
        return new ResultBody().code(ErrorCode.FAIL.getCode()).msg(ErrorCode.FAIL.getMessage());
    }
    
    @Override
    public String toString() {
 
        return "ResultBody{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", path='" + path + '\'' +
                ", data=" + data +
                ", httpStatus=" + httpStatus +
                ", extra=" + extra +
                ", timestamp=" + timestamp +
                '}';
    }
}

public enum ErrorCode {
 
    OK(0, "success"),
    FAIL(1000, "fail"),
    ALERT(1001, "alert"),
}

The front end is based on this code To judge success or failure.


Related articles: