Revise controller error handling
[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.HttpStatus;
28 import org.springframework.http.ResponseEntity;
29 import org.springframework.web.bind.annotation.ControllerAdvice;
30 import org.springframework.web.bind.annotation.ExceptionHandler;
31 import org.springframework.web.client.HttpStatusCodeException;
32 import org.springframework.web.client.RestClientResponseException;
33 import org.springframework.web.context.request.WebRequest;
34 import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
35
36 /**
37  * Catches certain exceptions. This controller advice factors out try-catch
38  * blocks in many controller methods.
39  * 
40  * Also see:<br>
41  * https://www.baeldung.com/exception-handling-for-rest-with-spring
42  * https://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services
43  */
44 @ControllerAdvice
45 public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
46
47         // Superclass has "logger" that is exposed here, so use a different name
48         private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
49
50         /**
51          * Logs the error and generates a JSON response when a REST controller method
52          * takes a RestClientResponseException. This is thrown by the Http client when a
53          * remote method returns a non-2xx code. All the controller methods are proxies
54          * in that they just forward the request along to a remote system, so if that
55          * remote system fails, return 502 plus some details about the failure, rather
56          * than the generic 500 that Spring-Boot will return on an uncaught exception.
57          * 
58          * Why 502? I quote: <blockquote>HTTP server received an invalid response from a
59          * server it consulted when acting as a proxy or gateway.</blockquote>
60          * 
61          * @param ex
62          *                    The exception
63          * 
64          * @param request
65          *                    The original request
66          * 
67          * @return A response entity with status code 502 plus some details in the body.
68          */
69         @ExceptionHandler({ RestClientResponseException.class })
70         public final ResponseEntity<ErrorTransport> handleProxyMethodException(Exception ex, WebRequest request) {
71                 // Capture the full stack trace in the log.
72                 log.error("handleProxyMethodException: request {}, exception {}", request.getDescription(false), ex);
73                 if (ex instanceof HttpStatusCodeException) {
74                         HttpStatusCodeException hsce = (HttpStatusCodeException) ex;
75                         return new ResponseEntity<>(new ErrorTransport(hsce.getRawStatusCode(), hsce.getResponseBodyAsString(),
76                                         ex.toString(), request.getDescription(false)), HttpStatus.BAD_GATEWAY);
77                 } else {
78                         return new ResponseEntity<>(new ErrorTransport(500, ex), HttpStatus.BAD_GATEWAY);
79                 }
80         }
81
82 }