我的Spring Boot + Jersey REST服務無法按預期工作。Jersey ExceptionMapper不映射異常
EmailExistsException在UserController中引發,但我只收到錯誤500.所有的時間。而我的例外情況沒有記錄。
我懷疑有一些配置問題與異常處理,但不知道在哪裏設置它。有什麼建議麼?
@POST
@Path("register")
@Produces(MediaType.APPLICATION_JSON)
public Response register(NewUserPayload newUserPayload) throws EmailExistsException, MessagingException
EmailExistsExceptionMapper
@Provider
public class EmailExistsExceptionMapper extends AbstractExceptionMapper implements
ExceptionMapper<EmailExistsException>
{
@Override
public Response toResponse(EmailExistsException e)
{
ResponseEntity re = new ResponseEntity(org.springframework.http.HttpStatus.BAD_REQUEST);
return this.errorResponse(HttpStatus.BAD_REQUEST_400, re, e);
}
}
AbstractExceptionMapper
@Slf4j
public abstract class AbstractExceptionMapper
{
protected Response errorResponse(int status, ResponseEntity responseEntity, Throwable t)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
log.error(sw.toString()); // logging stack trace.
return customizeResponse(status, responseEntity);
}
private Response customizeResponse(int status, ResponseEntity responseEntity)
{
return Response.status(status).entity(responseEntity).build();
}
}
的build.gradle
compile("org.springframework.boot:spring-boot-starter-web") {
exclude module: 'spring-boot-starter-tomcat'
}
compile "org.springframework.boot:spring-boot-starter-jetty"
compile "org.springframework.boot:spring-boot-starter-security"
compile "org.springframework.boot:spring-boot-starter-aop"
compile "org.springframework.boot:spring-boot-starter-data-jpa"
compile "org.springframework.boot:spring-boot-starter-thymeleaf"
compile "org.springframework.boot:spring-boot-starter-jersey"
compile 'org.springframework.boot:spring-boot-starter-mail'
[球衣文檔]中沒有關於此配置的信息(https://jersey.java.net/documentation/latest/representations.html#d0e6653)。 'package'聲明是否會避免你聲明控制器? – herau
我在互聯網上的一些代碼片段中找到它。我現在在斯卡拉,所以不能告訴你更多關於它的信息。 – Reeebuuk
謝謝!事實證明,你必須顯式地註冊(YourExceptionMapper.class),或者通過packages(「YourExceptionMapperPackage」)把它放在一個掃描的包中。在找到答案之前,我花了幾個小時試圖弄清楚這一點。 –