1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.mcr.acl.accesskey.restapi.v2;
20
21 import java.util.Optional;
22
23 import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyException;
24 import org.mycore.mcr.acl.accesskey.exception.MCRAccessKeyNotFoundException;
25 import org.mycore.restapi.v2.MCRErrorResponse;
26
27 import jakarta.ws.rs.WebApplicationException;
28 import jakarta.ws.rs.core.Context;
29 import jakarta.ws.rs.core.Request;
30 import jakarta.ws.rs.core.Response;
31 import jakarta.ws.rs.ext.ExceptionMapper;
32 import jakarta.ws.rs.ext.Provider;
33
34 @Provider
35 public class MCRRestAccessKeyExceptionMapper implements ExceptionMapper<MCRAccessKeyException> {
36
37 @Context
38 Request request;
39
40 @Override
41 public Response toResponse(MCRAccessKeyException exception) {
42 return fromException(exception);
43 }
44
45 public static Response fromException(MCRAccessKeyException e) {
46 if (e instanceof MCRAccessKeyNotFoundException) {
47 return getResponse(e, Response.Status.NOT_FOUND.getStatusCode(),
48 e.getErrorCode());
49 }
50 return getResponse(e, Response.Status.BAD_REQUEST.getStatusCode(),
51 e.getErrorCode());
52 }
53
54 private static Response getResponse(Exception e, int statusCode, String errorCode) {
55 MCRErrorResponse response = MCRErrorResponse.fromStatus(statusCode)
56 .withCause(e)
57 .withMessage(e.getMessage())
58 .withDetail(Optional.of(e)
59 .map(ex -> (ex instanceof WebApplicationException) ? ex.getCause() : ex)
60 .map(Object::getClass)
61 .map(Class::getName)
62 .orElse(null))
63 .withErrorCode(errorCode);
64
65 return Response.status(response.getStatus())
66 .entity(response)
67 .build();
68 }
69 }