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 lombok.extern.slf4j.Slf4j;
import org.gringlobal.api.exception.NotFoundElement;
import org.springframework.http.HttpStatus;
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.context.request.WebRequest;

/**
 * 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> handleMissingAccession(NotFoundElement ex, WebRequest request) {
		log.warn("Returning BrAPI error: {}", ex.getMessage());
		return new BrAPIResponse<>(ex);
	}

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