Skip to content

Commit

Permalink
Add exception mappers for custom exceptions
Browse files Browse the repository at this point in the history
* Exception mapper for TaskNotFound exceptions - returns a 404 Not Found response
* Exception mapper for InvalidTaskData exceptions - returns a 400 Bad Request response
  • Loading branch information
nikist97 committed Jun 28, 2022
1 parent 179c1ea commit 498169e
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/main/java/taskmanagement/api/ApplicationConfig.java
Expand Up @@ -18,6 +18,8 @@ public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig(ServiceLocator serviceLocator) {
register(TaskManagementResource.class);
register(JsonObjectMapperProvider.class);
register(InvalidTaskDataExceptionMapper.class);
register(TaskNotFoundExceptionMapper.class);

// bridge the Guice container (Injector) into the HK2 container (ServiceLocator)
Injector injector = Guice.createInjector(new ApplicationModule());
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/taskmanagement/api/ExceptionMessage.java
@@ -0,0 +1,14 @@
package taskmanagement.api;

public class ExceptionMessage {

private final String message;

public ExceptionMessage(String message) {
this.message = message;
}

public String getMessage() {
return message;
}
}
@@ -0,0 +1,20 @@
package taskmanagement.api;

import taskmanagement.exceptions.InvalidTaskDataException;

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

public class InvalidTaskDataExceptionMapper implements ExceptionMapper<InvalidTaskDataException> {

@Override
public Response toResponse(InvalidTaskDataException exception) {
return Response
.status(Response.Status.BAD_REQUEST)
.entity(new ExceptionMessage(exception.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
}

}
20 changes: 20 additions & 0 deletions src/main/java/taskmanagement/api/TaskNotFoundExceptionMapper.java
@@ -0,0 +1,20 @@
package taskmanagement.api;

import taskmanagement.exceptions.TaskNotFoundException;

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

public class TaskNotFoundExceptionMapper implements ExceptionMapper<TaskNotFoundException> {

@Override
public Response toResponse(TaskNotFoundException exception) {
return Response
.status(Response.Status.NOT_FOUND)
.entity(new ExceptionMessage(exception.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
}

}

0 comments on commit 498169e

Please sign in to comment.