| /** |
| * Licensed under the Apache License, Version 2.0 (the "License"); |
| * you may not use this file except in compliance with the License. |
| * You may obtain a copy of the License at |
| * |
| * http://www.apache.org/licenses/LICENSE-2.0 |
| * |
| * Unless required by applicable law or agreed to in writing, software |
| * distributed under the License is distributed on an "AS IS" BASIS, |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| * See the License for the specific language governing permissions and |
| * limitations under the License. |
| */ |
| package org.apache.pulsar.manager.controller.exception; |
| |
| import org.springframework.http.HttpHeaders; |
| import org.springframework.http.MediaType; |
| import org.springframework.http.ResponseEntity; |
| import org.springframework.web.bind.annotation.ExceptionHandler; |
| import org.springframework.web.bind.annotation.RestControllerAdvice; |
| import org.springframework.web.context.request.WebRequest; |
| import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; |
| |
| import java.util.List; |
| import java.util.stream.Collectors; |
| |
| import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; |
| |
| @RestControllerAdvice |
| public class CustomizeExceptionHandler extends ResponseEntityExceptionHandler { |
| |
| @ExceptionHandler({InvalidRequestException.class}) |
| public ResponseEntity<Object> handleInvalidRequest(RuntimeException e, WebRequest request) { |
| InvalidRequestException ire = (InvalidRequestException) e; |
| |
| List<FieldErrorResource> errorResources = ire.getErrors().getFieldErrors().stream().map(fieldError -> |
| new FieldErrorResource( |
| fieldError.getObjectName(), |
| fieldError.getField(), |
| fieldError.getCode(), |
| fieldError.getDefaultMessage())).collect(Collectors.toList()); |
| |
| ErrorResource error = new ErrorResource(errorResources); |
| |
| HttpHeaders headers = new HttpHeaders(); |
| headers.setContentType(MediaType.APPLICATION_JSON); |
| |
| return handleExceptionInternal(e, error, headers, UNPROCESSABLE_ENTITY, request); |
| } |
| } |