ErrorController.java

/*
 * Copyright 2022 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.mvc;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ErrorController {

	@RequestMapping(value = "/error", method = RequestMethod.GET)
	public ModelAndView renderErrorPage(HttpServletRequest httpRequest) {

		ModelAndView errorPage = new ModelAndView("/errors/error");
		int httpErrorCode = getErrorCode(httpRequest);

		errorPage.addObject("httpErrorCode", httpErrorCode);
		errorPage.addObject("errorUri", httpRequest.getAttribute("javax.servlet.error.request_uri"));
		errorPage.addObject("errorMessage", httpRequest.getAttribute("javax.servlet.error.message"));
		errorPage.addObject("exception", httpRequest.getAttribute("javax.servlet.error.exception"));
		return errorPage;
	}


	@GetMapping({ "/access-denied" })
	public String accessDenied(final ModelMap model) {
		final AccessDeniedException e = new AccessDeniedException("Access denied");
		model.addAttribute("exception", e);
		model.addAttribute("errorMessage", e.getMessage());
		model.addAttribute("httpErrorCode", 403);
		return "/errors/error";
	}

	private int getErrorCode(HttpServletRequest httpRequest) {
		var statusCode = httpRequest.getAttribute("javax.servlet.error.status_code");
		return statusCode == null ? -1 : (Integer) statusCode;
	}
}