2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 Nordix Foundation
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.ncmp.dmi.exception;
23 import lombok.extern.slf4j.Slf4j;
24 import org.onap.cps.ncmp.dmi.model.ErrorMessage;
25 import org.onap.cps.ncmp.dmi.rest.controller.DmiRestController;
26 import org.springframework.http.HttpStatus;
27 import org.springframework.http.ResponseEntity;
28 import org.springframework.web.bind.annotation.ExceptionHandler;
29 import org.springframework.web.bind.annotation.RestControllerAdvice;
32 @RestControllerAdvice(assignableTypes = {DmiRestController.class})
33 public class DmiExceptionHandler {
35 private DmiExceptionHandler() {
39 * Default exception handler.
41 * @param exception the exception to handle
42 * @return response with response code 500.
45 public static ResponseEntity<Object> handleInternalServerErrorExceptions(final Exception exception) {
46 return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, exception);
49 @ExceptionHandler({ModulesNotFoundException.class, ModuleResourceNotFoundException.class})
50 public static ResponseEntity<Object> handleNotFoundExceptions(final DmiException exception) {
51 return buildErrorResponse(HttpStatus.NOT_FOUND, exception);
54 @ExceptionHandler({CmHandleRegistrationException.class, DmiException.class})
55 public static ResponseEntity<Object> handleAnyOtherDmiExceptions(final DmiException exception) {
56 return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, exception);
59 private static ResponseEntity<Object> buildErrorResponse(final HttpStatus httpStatus, final Exception exception) {
60 logForNonDmiException(exception);
61 final var errorMessage = new ErrorMessage();
62 errorMessage.setStatus(httpStatus.toString());
63 errorMessage.setMessage(exception.getMessage());
64 errorMessage.setDetails(exception instanceof DmiException ? ((DmiException) exception).getDetails() :
65 "Check logs for details.");
66 return new ResponseEntity<>(errorMessage, httpStatus);
69 private static void logForNonDmiException(final Exception exception) {
70 if (exception.getCause() != null || !(exception instanceof DmiException)) {
71 log.error("Exception occurred", exception);