برنامه نویسی

REST API Exception Handler – انجمن DEV

import io.sentry.Sentry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;
import java.nio.file.AccessDeniedException;

@Slf4j
@RestControllerAdvice
public class CustomExceptionHandler {

    /**
     * 403 Forbidden
     * @param fe
     * @return
     */
    @ExceptionHandler({AccessDeniedException.class, HttpClientErrorException.Forbidden.class})
    public ResponseEntity<CustomExceptionEntity> forbiddenException(final Exception fe) {
        fe.printStackTrace();

        return ResponseEntity
                .status(HttpStatus.FORBIDDEN.value())
                .body(CustomExceptionEntity.builder()
                        .errorCode(String.valueOf(HttpStatus.FORBIDDEN.value()))
                        .errorMessage(fe.getMessage())
                        .build());
    }

    /**
     * 500 Internal Server Error
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    public ResponseEntity<CustomExceptionEntity> internalServerException(final Exception e) {
        e.printStackTrace();
        Sentry.captureException(e);

        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .body(CustomExceptionEntity.builder()
                        .errorCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()))
                        .errorMessage(e.getMessage())
                        .build());
    }

    @ExceptionHandler({CustomApiException.class})
    public ResponseEntity<CustomExceptionEntity> customApiException(final CustomApiException ce) {
        ce.printStackTrace();
        Sentry.captureException(ce);

        return ResponseEntity
                .status(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .body(CustomExceptionEntity.builder()
                        .errorCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()))
                        .errorMessage(ce.getMessage())
                        .build());
    }
}
وارد حالت تمام صفحه شوید

از حالت تمام صفحه خارج شوید

نوشته های مشابه

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *

دکمه بازگشت به بالا