您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Spring Boot中,如何在JSON中抛出异常

在Spring Boot中,如何在JSON中抛出异常

假设您有一个自定义的Exception类NotFoundException及其实现,如下所示:

public class NotFoundException extends Exception {

    private int errorCode;
    private String errorMessage;

    public NotFoundException(Throwable throwable) {
        super(throwable);
    }

    public NotFoundException(String msg, Throwable throwable) {
        super(msg, throwable);
    }

    public NotFoundException(String msg) {
        super(msg);
    }

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


    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    @Override
    public String toString() {
        return this.errorCode + " : " + this.getErrorMessage();
    }
}

现在,您想从控制器抛出一些异常。如果抛出异常,则必须从标准错误处理程序类中捕获该异常,例如在spring说,它们提供了@ControllerAdvice注释以应用于制作标准错误处理程序类。当将它应用于类时,该spring组件(我是说您注释的类)可以捕获从控制器抛出的任何异常。但是我们需要使用适当的方法来映射异常类。因此,我们为您的异常NotFoundException处理程序定义了一种方法,如下所示。

@ControllerAdvice
public class RestErrorHandler {

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Object processValidationError(NotFoundException ex) {
        String result = ex.getErrorMessage();
        System.out.println("###########"+result);
        return ex;
    }
}

您想将 发送 ,因此在这里我们使用@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)。由于您使用了Spring- boot,因此您无需制作json字符串,只需简单的注释@ResponseBody即可自动完成。

Java 2022/1/1 18:13:36 有688人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶