View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
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          //LogManager.getLogger().error(response::getLogMessage, e);
65          return Response.status(response.getStatus())
66              .entity(response)
67              .build();
68      }
69  }