小编Ton*_*ony的帖子

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

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

应用程序异常.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;
    }
}
Run Code Online (Sandbox Code Playgroud)

用户控制器.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(), …
Run Code Online (Sandbox Code Playgroud)

java exception spring-boot

6
推荐指数
1
解决办法
2万
查看次数

标签 统计

exception ×1

java ×1

spring-boot ×1