Java 创建具有特定状态代码的自定义异常类

标签 java spring-boot exception

在 Spring Boot 中,我创建了具有特定状态代码的自定义异常类,并调用它来抛出异常,代码为:100 和消息:“没有内容”在 Controller ,但输出仍然返回“状态”:500 和“错误”: “内部服务器错误”

AppException.java

public 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"
}

最佳答案

如果您希望对 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;
    }
}

关于Java 创建具有特定状态代码的自定义异常类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849314/

相关文章:

Java AWT 应用程序窗口填充

java - 咖啡因 Springboot 集成

java - Spring Webflux如何验证所有步骤是否执行成功

Python 2.7 异常处理

java - Android Studio - 不同 dpi 的像素大小

java - 当前一个 SwingWorker 完成后,使用另一个参数值重新调用 SwingWorker

python - 用户定义的异常的好名字是什么?

c++ - 如何处理多个 Action 和异常

c# - 面向 C# 开发人员的 Java 教程

java - Spring 安全5 : No Beans of type BCryptPasswordEncoder found