Skip to content

GeneralExceptionHandlerer

seyyed edited this page Aug 5, 2021 · 2 revisions

This class Used For Handle General Exception And Service Exception

this class used For Parent Of ExceptionHandler

this Methode Used For Handle Service Exception

@ExceptionHandler(ServiceException.class)
    protected ResponseEntity<BaseDTO<Object>> serviceException(ServiceException e) {
        BaseDTO<Object> baseDTO = BaseDTO.builder().code(e.exceptionCode.toString()).message(e.exceptionMessage).status(Status.ERROR).build();
        return new ResponseEntity<>(baseDTO, e.httpStatus != null ? e.httpStatus : HttpStatus.INTERNAL_SERVER_ERROR);
    }

this Methode Used For Handle MethodArgumentNotValidException Exception Such As NotNull Javax anotations and Etc

@ExceptionHandler(MethodArgumentNotValidException.class)
    protected ResponseEntity<BaseDTO<String>> handleMethodArgumentNotValid(MethodArgumentNotValidException e) {
        FieldError error = e.getBindingResult().getFieldErrors().get(0);
        BaseDTO<String> baseDTO = BaseDTO.<String>builder().code(
                applicationResource.getResourceText("application.message.validationError.code"))
                .message(String.format(
                        applicationResource.getResourceText("application.message.validationError.message"),
                        (error.getField())
                )).status(Status.ERROR).build();
        return new ResponseEntity<>(baseDTO, HttpStatus.BAD_REQUEST);
    }

this methode used for Handle ConstraintViolationException Such Javax anotations and return the type of parameter that is not correct

@ExceptionHandler(ConstraintViolationException.class)
    protected ResponseEntity<BaseDTO<String>> handleConstraintViolationException(ConstraintViolationException e) {
        ConstraintViolation<?> error = e.getConstraintViolations().iterator().next();
        String fieldName = ((PathImpl) error.getPropertyPath()).getLeafNode().getName();
        BaseDTO<String> baseDTO = BaseDTO.<String>builder().code(
                applicationResource.getResourceText("application.message.validationError.code"))
                .message(String.format(
                        applicationResource.getResourceText("application.message.validationError.message"),
                        (fieldName)
                )).status(Status.ERROR).build();
        return new ResponseEntity<>(baseDTO, HttpStatus.BAD_REQUEST);
    }

Example

package app.ladderproject.integration.exception;

import app.ladderproject.framework.service.exception.GeneralExceptionHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;

@ControllerAdvice
public class MyExceptionHandler extends GeneralExceptionHandler {
}

Clone this wiki locally