Joaquín Reñé
2026-03-27 4ee50e257b32f6ec0f72907305d1f2b1212808a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/*
 * Copyright @ 2013 CurisTEC, S.A.S. All Rights Reserved.
 */
package net.curisit.securis;
import jakarta.persistence.EntityManager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.ForbiddenException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.SecurityContext;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.curisit.securis.services.exception.SeCurisServiceException;
import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
/**
* DefaultExceptionHandler
* <p>
* JAX-RS {@link ExceptionMapper} that normalizes error responses across the API.
* It also makes a best-effort to rollback and close a request-scoped {@link EntityManager}
* if still open.
*
* <p>Response strategy:
* <ul>
* <li>{@link ForbiddenException} → 401 UNAUTHORIZED with app-specific error headers.</li>
* <li>{@link SeCurisServiceException} → 418 (custom) with app error headers.</li>
* <li>Other exceptions → 500 with generic message and request context logging.</li>
* </ul>
*
* Headers:
* <ul>
* <li>{@code X-SECURIS-ERROR-MSG}</li>
* <li>{@code X-SECURIS-ERROR-CODE}</li>
* </ul>
*
* @author JRA
* Last reviewed by JRA on Oct 6, 2025.
*/
@Provider
public class DefaultExceptionHandler implements ExceptionMapper<Exception> {
   
   private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);
   
   /** Default status code used for application-defined errors. */
   public static final int DEFAULT_APP_ERROR_STATUS_CODE = 418;
   
   /** Header name carrying a human-readable error message. */
   public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG";
   
   /** Header name carrying a symbolic application error code. */
   public static final String ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE";
   /** Default constructor (logs instantiation). */
   public DefaultExceptionHandler() {
       LOG.info("Creating DefaultExceptionHandler ");
   }
   // Context objects injected by the runtime
   @Context
   HttpServletRequest request;
   @Context
   SecurityContext bsc;
   /**
   * toResponse
   * <p>
   * Map a thrown exception to an HTTP {@link Response}, releasing the {@link EntityManager}
   * if present.
   */
   @Override
   public Response toResponse(Exception e) {
       releaseEntityManager();
       if (e instanceof ForbiddenException) {
           LOG.warn("ForbiddenException: {}", e.toString());
           return Response.status(Status.UNAUTHORIZED)
                   .header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)
                   .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application")
                   .type(MediaType.APPLICATION_JSON)
                   .build();
       }
       if (e instanceof SeCurisServiceException) {
           LOG.warn("SeCurisServiceException: {}", e.toString());
           return Response.status(DEFAULT_APP_ERROR_STATUS_CODE)
                   .header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())
                   .header(ERROR_MESSAGE_HEADER, e.getMessage())
                   .type(MediaType.APPLICATION_JSON)
                   .build();
       }
       String path = request != null ? request.getPathInfo() : null;
       Object user = (bsc != null && bsc.getUserPrincipal() != null) ? bsc.getUserPrincipal() : null;
       String host = request != null ? request.getRemoteHost() : null;
       String ua = request != null ? request.getHeader("User-Agent") : null;
       String url = request != null ? String.valueOf(request.getRequestURL()) : null;
       LOG.error("Unexpected error accessing to '{}' by user: {}", path, user);
       LOG.error("Request sent from {}, with User-Agent: {}", host, ua);
       LOG.error("Request url: {}", url, e);
       /**
       LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());
       LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));
       LOG.error("Request url: " + request.getRequestURL(), e);
       */
       
       return Response.serverError()
               .header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString())
               .type(MediaType.APPLICATION_JSON)
               .build();
   }
   /**
   * releaseEntityManager
   * <p>
   * Best-effort cleanup: rollback active transaction (if joined) and close the {@link EntityManager}.
   */
   private void releaseEntityManager() {
       
       /**
       try {
           if (em != null && em.isOpen()) {
               LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());
               if (em.isJoinedToTransaction()) {
                   em.getTransaction().rollback();
                   LOG.info("ROLLBACK");
               }
               em.close();
           }
       } catch (Exception ex) {
           ex.printStackTrace();
           LOG.error("Error closing EM: {}, {}", em, ex);
       }
       */
   }
}