b1ac2e8fdb90bfef7bc643024789603cc79a7ba5
[portal/ric-dashboard.git] / webapp-backend / src / main / java / org / oransc / ric / portal / dashboard / controller / CustomResponseEntityExceptionHandler.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 AT&T Intellectual Property and Nokia
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20 package org.oransc.ric.portal.dashboard.controller;
21
22 import java.lang.invoke.MethodHandles;
23
24 import org.oransc.ric.portal.dashboard.model.ErrorTransport;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.springframework.http.HttpHeaders;
28 import org.springframework.http.HttpStatus;
29 import org.springframework.http.ResponseEntity;
30 import org.springframework.web.HttpRequestMethodNotSupportedException;
31 import org.springframework.web.bind.annotation.ControllerAdvice;
32 import org.springframework.web.bind.annotation.ExceptionHandler;
33 import org.springframework.web.client.HttpStatusCodeException;
34 import org.springframework.web.context.request.WebRequest;
35 import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
36
37 /**
38  * Catches Http status code exceptions and builds a response with code 502 and
39  * some details wrapped in an ErrorTransport object. This factors out try-catch
40  * blocks in many controller methods.
41  * 
42  * Why 502? I quote: <blockquote>HTTP server received an invalid response from a
43  * server it consulted when acting as a proxy or gateway.</blockquote>
44  *
45  * This class and the methods are not strictly necessary, the
46  * SimpleErrorController is invoked when any controller method takes an uncaught
47  * exception, but this approach provides a better response to the front end and
48  * doesn't signal internal server error.
49  * 
50  * Also see:<br>
51  * https://www.baeldung.com/exception-handling-for-rest-with-spring
52  * https://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services
53  */
54 @ControllerAdvice
55 public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
56
57         // Superclass has "logger" that is exposed here, so use a different name
58         private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
59
60         /*
61          * Generates the response when a REST controller method takes an
62          * HttpStatusCodeException.
63          * 
64          * It appears that the container internally redirects to /error because the web
65          * request that arrives here has URI /error, and {@link
66          * org.oransc.ric.portal.dashboard.controller.SimpleErrorController} runs before
67          * this.
68          * 
69          * @param ex The exception
70          * 
71          * @param request The original request
72          * 
73          * @return A response entity with status code 502 plus some details in the body.
74          */
75         @ExceptionHandler(HttpStatusCodeException.class)
76         public final ResponseEntity<ErrorTransport> handleHttpStatusCodeException(HttpStatusCodeException ex,
77                         WebRequest request) {
78                 log.warn("handleHttpStatusCodeException: request {}, status code {}", request.getDescription(false),
79                                 ex.getStatusCode());
80                 return new ResponseEntity<>(new ErrorTransport(ex.getRawStatusCode(), ex.getResponseBodyAsString(), ex),
81                                 HttpStatus.BAD_GATEWAY);
82         }
83
84         /*
85          * This exception also happens when Spring security denies access to a method
86          * due to missing/wrong roles (granted authorities). Override the method to
87          * answer permission denied, even though that may obscure a genuine developer
88          * error.
89          * 
90          * The web request that arrives here has URI /error; how to obtain the URI of
91          * the original request?!?
92          */
93         @Override
94         public final ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
95                         HttpHeaders headers, HttpStatus status, WebRequest request) {
96                 log.warn("handleHttpRequestMethodNotSupported: answering 'permission denied' for method {}", ex.getMethod());
97                 return new ResponseEntity<Object>(new ErrorTransport(HttpStatus.UNAUTHORIZED.value(),
98                                 "Permission denied for method " + ex.getMethod(), ex), HttpStatus.UNAUTHORIZED);
99         }
100
101 }