c34aa2fcb2c87f5b903a41eb5267857e93ef5aec
[portal/ric-dashboard.git] / dashboard / 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
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.exception.StatsManagerException;
25 import org.oransc.ric.portal.dashboard.exception.UnknownInstanceException;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import org.springframework.http.HttpStatus;
29 import org.springframework.http.ResponseEntity;
30 import org.springframework.web.bind.annotation.ControllerAdvice;
31 import org.springframework.web.bind.annotation.ExceptionHandler;
32 import org.springframework.web.client.HttpStatusCodeException;
33 import org.springframework.web.client.RestClientResponseException;
34 import org.springframework.web.context.request.WebRequest;
35 import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
36
37 /**
38  * Catches certain exceptions. This controller advice factors out try-catch
39  * blocks in many controller methods.
40  * 
41  * Also see:<br>
42  * https://www.baeldung.com/exception-handling-for-rest-with-spring
43  * https://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services
44  */
45 @ControllerAdvice
46 public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
47
48         // Superclass has "logger" that is exposed here, so use a different name
49         private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
50
51         /**
52          * Generates a message with an upper limit on size.
53          * 
54          * @param t
55          *              Throwable
56          * @return Message
57          */
58         private String getShortExceptionMessage(Throwable t) {
59                 final int enough = 256;
60                 String exString = t.toString();
61                 return exString.length() > enough ? exString.substring(0, enough) : exString;
62         }
63
64         /**
65          * Logs the error and generates a JSON response when a REST controller method
66          * takes a RestClientResponseException. This is thrown by the Http client when a
67          * remote method returns a non-2xx code. All the controller methods are proxies
68          * in that they just forward the request along to a remote system, so if that
69          * remote system fails, return 502 plus some details about the failure, rather
70          * than the generic 500 that Spring-Boot will return on an uncaught exception.
71          * 
72          * Why 502? I quote: <blockquote>HTTP server received an invalid response from a
73          * server it consulted when acting as a proxy or gateway.</blockquote>
74          * 
75          * @param ex
76          *                    The exception
77          * 
78          * @param request
79          *                    The original request
80          * 
81          * @return A response entity with status code 502 and an unstructured message.
82          */
83         @ExceptionHandler({ RestClientResponseException.class })
84         public final ResponseEntity<String> handleProxyMethodException(Exception ex, WebRequest request) {
85                 // Capture the full stack trace in the log.
86                 log.error("handleProxyMethodException: request {}, exception {}", request.getDescription(false), ex);
87                 if (ex instanceof HttpStatusCodeException) {
88                         HttpStatusCodeException hsce = (HttpStatusCodeException) ex;
89                         return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(hsce.getResponseBodyAsString());
90                 } else {
91                         return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(getShortExceptionMessage(ex));
92                 }
93         }
94
95         /**
96          * Logs a warning if an invalid RIC instance key is used.
97          * 
98          * @param ex
99          *                    The exception
100          * @param request
101          *                    The original request
102          * @return A response entity with status code 400 and an unstructured message.
103          */
104         @ExceptionHandler({ UnknownInstanceException.class })
105         public final ResponseEntity<String> handleUnknownInstanceException(Exception ex, WebRequest request) {
106                 log.warn("handleUnknownInstanceException: request {}, exception {}", request.getDescription(false),
107                                 ex.toString());
108                 return ResponseEntity.badRequest().body(getShortExceptionMessage(ex));
109         }
110
111         /**
112          * Logs a warning if a StatsManagerException is thrown.
113          * 
114          * @param ex
115          *                    The exception
116          * @param request
117          *                    The original request
118          * @return A response entity with status code 400 and an unstructured message.
119          */
120         @ExceptionHandler({ StatsManagerException.class })
121         public final ResponseEntity<String> handleStatsManagerException(Exception ex, WebRequest request) {
122                 log.warn("handleStatsManagerException: request {}, exception {}", request.getDescription(false), ex.toString());
123                 return ResponseEntity.badRequest().body(getShortExceptionMessage(ex));
124         }
125
126 }