自定義異常處理

直接上代碼this

public class UserNotExistException extends RuntimeException {

    /**
     *
     */
    private static final long serialVersionUID = -6112780192479692859L;

    private String id;

    public UserNotExistException(String id) {
        super("user not exist");
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}
//咱們傳了一個id,可是當咱們拋出異常時,只會有一個message提示,沒法獲得咱們想要的ID信息,
//這是由於父類值提供了返回message的方法

想要帶出咱們定義的變量數據,使用handler便可get

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(UserNotExistException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handleUserNotExistException(UserNotExistException ex) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", ex.getId());
        result.put("message", ex.getMessage());
        return result;
    }

}

當處理exception時,直接跳到這裏處理io

相關文章
相關標籤/搜索