溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring Boot異常統(tǒng)一處理方案設(shè)計(jì)

發(fā)布時間:2024-10-05 11:03:04 來源:億速云 閱讀:81 作者:小樊 欄目:編程語言

設(shè)計(jì)一個Spring Boot異常統(tǒng)一處理方案,可以提高系統(tǒng)的健壯性和可維護(hù)性。以下是一個基本的方案設(shè)計(jì):

1. 異常類設(shè)計(jì)

首先,定義一些自定義異常類,以便更好地管理和處理不同類型的異常。

public class CustomException extends RuntimeException {
    private int errorCode;
    private String errorMessage;

    public CustomException(int errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    // Getters and setters
}

2. 全局異常處理器

使用@ControllerAdvice注解來創(chuàng)建一個全局異常處理器類,該類將處理所有未被特定控制器處理的異常。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<ErrorResponse> handleCustomException(CustomException ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex.getErrorCode(), ex.getErrorMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
        ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred");
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

3. 錯誤響應(yīng)類

定義一個錯誤響應(yīng)類,用于封裝錯誤信息,使其易于前端處理。

public class ErrorResponse {
    private int errorCode;
    private String errorMessage;

    public ErrorResponse(int errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    // Getters and setters
}

4. 自定義注解

如果需要更細(xì)粒度的異常處理,可以創(chuàng)建自定義注解。

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomExceptionHandler {
    int errorCode() default 0;
    String errorMessage() default "An error occurred";
}

然后在控制器中使用該注解:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/test")
    @CustomExceptionHandler(errorCode = 1001, errorMessage = "Test error")
    public String test() {
        throw new CustomException(1001, "Test error");
    }
}

5. 異常日志記錄

為了更好地調(diào)試和監(jiān)控系統(tǒng),可以在全局異常處理器中記錄異常日志。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

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

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<ErrorResponse> handleCustomException(CustomException ex) {
        logger.error("CustomException: {}", ex.getMessage(), ex);
        ErrorResponse errorResponse = new ErrorResponse(ex.getErrorCode(), ex.getErrorMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
        logger.error("GenericException: {}", ex.getMessage(), ex);
        ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "An unexpected error occurred");
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

總結(jié)

通過上述設(shè)計(jì),可以實(shí)現(xiàn)一個基本的Spring Boot異常統(tǒng)一處理方案。該方案包括自定義異常類、全局異常處理器、錯誤響應(yīng)類、自定義注解以及異常日志記錄。根據(jù)具體需求,可以進(jìn)一步擴(kuò)展和優(yōu)化該方案。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI