BrAPIExceptionHandler.java

/*
 * Copyright 2020 Global Crop Diversity Trust
 *
 * 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.gringlobal.brapi;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

import lombok.extern.slf4j.Slf4j;
import org.gringlobal.api.exception.NotFoundElement;
import org.gringlobal.api.exception.InvalidApiUsageException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

/**
 * BrAPI exception handler returns errors in {@link BrAPIResponse#metadata}.
 *
 * @author Matija Obreza
 */
@ControllerAdvice(basePackages = { "org.gringlobal.brapi" })
@Slf4j
public class BrAPIExceptionHandler {

	@ResponseStatus(code = HttpStatus.NOT_FOUND)
	@ExceptionHandler(NotFoundElement.class)
	@ResponseBody
	public BrAPIResponse<Exception> handle404(NotFoundElement ex, HttpServletRequest request) {
		log.error("Not found {} {}: {}", request.getMethod(), request.getRequestURL(), ex.toString());
		return new BrAPIResponse<>(ex);
	}

	@ResponseStatus(code = HttpStatus.BAD_REQUEST)
	@ExceptionHandler({
		HttpMessageNotReadableException.class, MethodArgumentTypeMismatchException.class, MissingServletRequestParameterException.class, ConstraintViolationException.class,
		InvalidApiUsageException.class, IllegalArgumentException.class
	})
	@ResponseBody
	public BrAPIResponse<Exception> handleClientError(Exception ex, HttpServletRequest request) {
		log.error("Bad request {} {}: {}", request.getMethod(), request.getRequestURL(), ex.toString());
		return new BrAPIResponse<>(ex);
	}

	/**
	 * Handle request method fail.
	 */
	@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
	@ExceptionHandler(value = { HttpRequestMethodNotSupportedException.class })
	public BrAPIResponse<Exception> handleRequestMethodFail(final HttpServletRequest req, final HttpRequestMethodNotSupportedException e) {
		log.warn("Request method {} not supported for URL {}", e.getMethod(), req.getRequestURL());
		return new BrAPIResponse<>(e);
	}

	@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Throwable.class)
	@ResponseBody
	public BrAPIResponse<Exception> handleServerError(Exception ex, HttpServletRequest request) {
		if (log.isInfoEnabled()) {
			log.error("BrAPI exception {} {}: {}", request.getMethod(), request.getRequestURL(), ex.toString(), ex);
		} else {
			log.error("BrAPI exception {} {}: {}", request.getMethod(), request.getRequestURL(), ex.toString());
		}
		return new BrAPIResponse<>(ex);
	}
}