2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2021 AT&T Intellectual Property. All rights reserved.
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 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 * ============LICENSE_END=========================================================
20 package org.o.ran.oam.nf.oam.adopter.app.controller;
22 import java.util.HashMap;
24 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.exceptions.AlreadyPresentException;
25 import org.o.ran.oam.nf.oam.adopter.pm.rest.manager.exceptions.NotFoundException;
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.validation.FieldError;
31 import org.springframework.web.bind.MethodArgumentNotValidException;
32 import org.springframework.web.bind.annotation.ExceptionHandler;
33 import org.springframework.web.bind.annotation.ResponseStatus;
34 import org.springframework.web.bind.annotation.RestControllerAdvice;
37 public class RestExceptionHandler {
38 private static final Logger LOG = LoggerFactory.getLogger(RestExceptionHandler.class);
41 * Handle Already Present Exceptions.
43 @ExceptionHandler({AlreadyPresentException.class})
44 public static ResponseEntity<Object> handleBadRequestExceptions(final AlreadyPresentException exception) {
45 LOG.error("Request failed", exception);
48 .body(exception.getMessage());
52 * Handle Not Found Exceptions.
54 @ExceptionHandler({NotFoundException.class})
55 public static ResponseEntity<Object> handleNotFoundExceptions(final NotFoundException exception) {
56 LOG.error("Request failed", exception);
57 return ResponseEntity.notFound().build();
61 * Handle MethodArgument Not Valid Exceptions.
63 @ResponseStatus(HttpStatus.BAD_REQUEST)
64 @ExceptionHandler(MethodArgumentNotValidException.class)
65 public Map<String, String> handleValidationExceptions(final MethodArgumentNotValidException ex) {
66 final Map<String, String> errors = new HashMap<>();
67 ex.getBindingResult().getAllErrors().forEach((error) -> {
68 final String fieldName = ((FieldError) error).getField();
69 final String errorMessage = error.getDefaultMessage();
70 errors.put(fieldName, errorMessage);