com.naharoo.commons.mstoolkit.rest.exceptionhandler.AccessDeniedExceptionHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ms-toolkit-rest-exception-handler-starter Show documentation
Show all versions of ms-toolkit-rest-exception-handler-starter Show documentation
Common exceptions handler as a Spring Boot Starter
package com.naharoo.commons.mstoolkit.rest.exceptionhandler;
import com.naharoo.commons.mstoolkit.exceptions.IssueType;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.naharoo.commons.mstoolkit.exceptions.CommonIssueType.FORBIDDEN_ACCESS;
@ControllerAdvice
@ConditionalOnProperty(prefix = "ms-toolkit.rest-exception-handler.handlers.enabled", name = "FORBIDDEN_ACCESS", havingValue = "true", matchIfMissing = true)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass(name = "org.springframework.security.access.AccessDeniedException")
public class AccessDeniedExceptionHandler {
private static final String ERROR_MESSAGE = "Access is denied.";
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity handleException(
final AccessDeniedException exception,
final HttpServletRequest request
) {
final Set issueTypes = new HashSet<>();
issueTypes.add(FORBIDDEN_ACCESS);
final List errorMessages = new ArrayList<>();
errorMessages.add(ERROR_MESSAGE);
final ApiErrorResponse apiErrorResponse = new ApiErrorResponse(
HttpStatus.FORBIDDEN.value(),
issueTypes,
errorMessages,
LocalDateTime.now()
);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(apiErrorResponse);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy