BrAPIExceptionHandler.java

/*
 * Copyright 2017 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.genesys.server.brapi;

import com.fasterxml.jackson.core.JsonProcessingException;

import org.genesys.brapi.model.BrAPIResponse;
import org.genesys.server.exception.NoSuchAccessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.genesys.server.brapi" })
public class BrAPIExceptionHandler {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());

	@ResponseStatus(code = HttpStatus.NOT_FOUND)
	@ExceptionHandler(NoSuchAccessionException.class)
	@ResponseBody
	public BrAPIResponse<Exception> handleMissingAccession(NoSuchAccessionException ex, WebRequest request) throws JsonProcessingException {
		LOG.warn("Returning BrAPI error: {}", ex.getMessage());
		return new BrAPIResponse<>(ex);
	}

	@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public BrAPIResponse<Exception> handleServerError(Exception ex, WebRequest request) {
		LOG.warn("General exception: {}", ex.toString(), ex);
		return new BrAPIResponse<>(ex);
	}
}