栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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
处理程序定义了一种方法,如下所示。

@ControllerAdvicepublic 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;    }}

您想将 http状态 发送 到内部服务器error(500)
,因此在这里我们使用

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/615617.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号