![](/img/trans.png)
[英]jersey: WebApplicationException not displaying custom reason phrase?
[英]Custom HTTP reason phrase using ExceptionMapper
我定義了以下異常映射器來處理自定義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
消息,而不是我在“響應”中設置的自定義消息。
為什么會這樣?
它顯示了標准響應,因為您沒有為響應設置主體,而只是設置狀態。 您必須像這樣傳遞自定義響應:
Response response = Response.status (Response.Status.INTERNAL_SERVER_ERROR).entity(CustomResponse).build ();
我對設計不滿意,但可能會是這樣:
HttpCustomExceptionStatusType status = new HttpCustomExceptionStatusType (Response.Status.INTERNAL_SERVER_ERROR, e.getMessage ())
Response response = Response.status (status).entity(status).build ();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.