使用ExceptionMapper的自定义HTTP原因短语 [英] Custom HTTP reason phrase using ExceptionMapper

查看:207
本文介绍了使用ExceptionMapper的自定义HTTP原因短语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已定义以下异常映射器来处理自定义HttpCustomException

I have defined the following Exception Mapper to handle the custom HttpCustomException

package com.myapp.apis;

import com.myapp.apis.model.HttpCustomException;
import com.myapp.apis.model.HttpCustomExceptionStatusType;
import com.myapp.apis.model.HttpCustomNotAuthorizedException;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class HttpCustomExceptionMapper implements ExceptionMapper <HttpCustomException> {

  @Override
  public Response toResponse (HttpCustomException e) {
    Response response = Response.status (new HttpCustomExceptionStatusType (Response.Status.UNAUTHORIZED, e.getMessage ())).build ();
    if (e instanceof HttpCustomNotAuthorizedException) {
      response = Response.status (new HttpCustomExceptionStatusType (Response.Status.INTERNAL_SERVER_ERROR, e.getMessage ())).build ();
    }

    System.out.println ("HttpCustomExceptionMapper: " + response.getStatus () + ", " + response.getStatusInfo ().getReasonPhrase ());
    return response;
  }
}

在代码中抛出HttpCustomNotAuthorizedException时,我可以在catalina.out中看到在toResponse方法末尾定义的日志消息.因此,在请求处理期间将调用HttpCustomExceptionMapper类.但是,在最终响应中,我在客户端看到的是,我只看到标准的Not Authorized消息,而不是我在响应中设置的自定义消息.

When a HttpCustomNotAuthorizedException is thrown in the code, I can see the log message defined in the end of the toResponse method, in catalina.out. So, the HttpCustomExceptionMapper class is being invoked during the request processing. But, in the final response, I see in the client, I only see the standard Not Authorized message and not the custom message I set in the Response.

为什么会这样?

推荐答案

您应该注意,当前版本的HTTP协议(HTTP/2)完全不支持原因短语.它已从协议中删除.

You should note that the current version of HTTP protocol (HTTP/2) does not support a reason phrase at all. It has been removed from the protocol.

因此,从Tomcat 9.0起已删除了对发送原因短语的支持.在Tomcat 7.0中,默认情况下已禁用8.5对发送自定义原因短语的支持(可以通过连接器上设置sendReasonPhrase="true"

Thus support for sending a reason phrase has been removed from Tomcat 9.0 onwards. In Tomcat 7.0, 8.5 support for sending a custom reason phrase is off by default (can be enabled with a system property, org.apache.coyote.USE_CUSTOM_STATUS_MSG_IN_HEADER). In 8.5 you also should set sendReasonPhrase="true" on a Connector.

这篇关于使用ExceptionMapper的自定义HTTP原因短语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆