为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 473 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号