如何使用Spring MVC返回自定义http错误代码?

时间:2022-02-26 05:39:04

My intention is to return custom http error codes with Spring MVC, for example: 601, 602 ... so that the customer can clearly differentiate between errors.

我的目的是使用Spring MVC返回自定义http错误代码,例如:601,602 ......这样客户就可以清楚地区分错误。

    @ExceptionHandler(Exception.class)
    public @ResponseBody
    ErrorAlmacen generalExceptionHandler(Exception exception, HttpServletResponse response) {
        response.setStatus(601);
        ErrorAlmacen error = new ErrorAlmacen();
        ...
        return error;
    }

But when my @ExceptionHandler set these values ​​in the respose object, Spring somehow translates to 200.

但是当我的@ExceptionHandler在respose对象中设置这些值时,Spring会以某种方式转换为200。

Is it possible to do what I am trying, or Spring is not going to allow me?

是否有可能做我正在尝试的事情,或者Spring不会允许我?

1 个解决方案

#1


0  

What you're trying to do is not possible to accomplish.

你要做的事是不可能完成的。

HTTP is a well-known protocol which can not re-design for your own usage.

HTTP是一种众所周知的协议,无法为您自己的用途重新设计。

A protocol is the "language", the rules that 2 parties aware of and now how to "speak" and communicate with each other.

协议是“语言”,是双方意识到的规则,现在如何“说话”并相互通信。

When you deploy your web application to a web server, that web server can respond to HTTP requests from the client, the client would be a browser of an end user. and that browser expects to receive only and only 200 code for an OK response, and no other HTTP code for OK approval.

将Web应用程序部署到Web服务器时,该Web服务器可以响应来自客户端的HTTP请求,客户端将是最终用户的浏览器。并且该浏览器期望仅接收200个代码以获得OK响应,并且没有其他HTTP代码用于OK批准。

Your browser knows to resolve the status 200 and not the 602 that you wish to use.

您的浏览器知道要解析状态200而不是您希望使用的602。

That is how browsers are built, and you can't change the protocol.

这就是浏览器的构建方式,您无法更改协议。

#1


0  

What you're trying to do is not possible to accomplish.

你要做的事是不可能完成的。

HTTP is a well-known protocol which can not re-design for your own usage.

HTTP是一种众所周知的协议,无法为您自己的用途重新设计。

A protocol is the "language", the rules that 2 parties aware of and now how to "speak" and communicate with each other.

协议是“语言”,是双方意识到的规则,现在如何“说话”并相互通信。

When you deploy your web application to a web server, that web server can respond to HTTP requests from the client, the client would be a browser of an end user. and that browser expects to receive only and only 200 code for an OK response, and no other HTTP code for OK approval.

将Web应用程序部署到Web服务器时,该Web服务器可以响应来自客户端的HTTP请求,客户端将是最终用户的浏览器。并且该浏览器期望仅接收200个代码以获得OK响应,并且没有其他HTTP代码用于OK批准。

Your browser knows to resolve the status 200 and not the 602 that you wish to use.

您的浏览器知道要解析状态200而不是您希望使用的602。

That is how browsers are built, and you can't change the protocol.

这就是浏览器的构建方式,您无法更改协议。