我的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”)把它放在一个扫描的包中。在找到答案之前,我花了几个小时试图弄清楚这一点。 –