亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java創建具有特定狀態碼的自定義異常類

Java創建具有特定狀態碼的自定義異常類

瀟瀟雨雨 2022-07-06 19:09:30
在 Spring Boot 中,我創建了具有特定狀態代碼的自定義異常類,并調用它以在控制器上拋出異常代碼:100 和消息:“沒有內容”,但輸出仍然返回“狀態”:500 和“錯誤”: “內部服務器錯誤”AppException.javapublic class AppException extends RuntimeException {    private static final long serialVersionUID = 1L;    private final Integer code;    public AppException(Integer code, String message) {        super(message);        this.code = code;    }    public Integer getCode() {        return code;    }}UserController.java@RestController@RequestMapping("/api/user")public class UserController {    @Autowired    private UserService userService;    @GetMapping()    public ApiResponseDto getAllUsers(Pageable pageable) {        Page<User> users = userService.getAllUsers(pageable);        if (users.getSize() < 0) {            throw new AppException(100, "No have content");        }        return new ApiResponseDto(HttpStatus.OK.value(), users);    }實際輸出:{    "timestamp": 1550987372934,    "status": 500,    "error": "Internal Server Error",    "exception": "com.app.core.exception.AppException",    "message": "No have content",    "path": "/api/user"}我的期望:{    "timestamp": 1550987372934,    "status": 100,    "error": "No have content",    "exception": "com.app.core.exception.AppException",    "message": "No have content",    "path": "/api/user"}
查看完整描述

3 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

如果您希望對 API 進行全局異常處理,并且更喜歡自定義錯誤響應,您可以添加@ControllerAdvice:


@ControllerAdvice

public class ApiExceptionHandler {


    @ExceptionHandler({ ApiException.class })

    protected ResponseEntity<ApiErrorResponse> handleApiException(ApiException ex) {

        return new ResponseEntity<>(new ApiErrorResponse(ex.getStatus(), ex.getMessage(), Instant.now()), ex.getStatus());

    }

}


// you can put any information you want in ApiErrorResponse 

public class ApiErrorResponse {


    private final HttpStatus status;

    private final String message;

    private final Instant timestamp;


    public ApiError(HttpStatus status, String message, Instant timestamp) {

        this.status= status;

        this.message = message;

        this.timestamp = timestamp;

    }


    public HttpStatus getStatus() { 

        return this.status; 

    }


    public String getMessage() {

        return this.message;

    }


    public Instant getTimestamp() {

        return this.timestamp;

    }

}


// your custom ApiException class

public class ApiException extends RuntimeException {


    private final HttpStatus status;


    public ApiException(HttpStatus status, String message) {

        super(message);

        this.status = status;

    }


    public HttpStatus getStatus() {

        return this.status;

    }

}


查看完整回答
反對 回復 2022-07-06
?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

如果您需要有限數量的不同錯誤消息,或者您想多次重復使用相同的錯誤消息,那么您只需要這樣:


@ResponseStatus(value = HttpStatus.CONTINUE, reason = "No have content")

public class AppException extends RuntimeException {

    private static final long serialVersionUID = 1L;

}

不需要任何額外的類和處理程序。您的代碼將清晰而簡單。


您可以像這樣簡單地提高它:


throw new AppException();


查看完整回答
反對 回復 2022-07-06
?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

有多種方法可以實現這一點:


異常處理程序


您可以@ExceptionHandler在控制器中添加帶注釋的方法:


@ExceptionHandler({ CustomException1.class, CustomException2.class })

public void handleException() {

//

}

處理程序異常解析器


您還可以實現自定義解析器來攔截所有異常并通過覆蓋doResolveException方法來全局處理它們


可以在此處找到有關上述兩種方法的更多詳細信息:https ://www.baeldung.com/exception-handling-for-rest-with-spring


查看完整回答
反對 回復 2022-07-06
  • 3 回答
  • 0 關注
  • 349 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號