2

I have a method that should return Department but the method findById(deptNo) returns an Optional. I need to map a custom exception with HTTP 404 status to throw it if the given id doesn't exist in the database.

 @Override
public Department getById(String deptNo) throws DepartmentNotFoundException {
    try {
        Department department = departmentRepository.findById(deptNo).orElseThrow();
        return department;
    } catch (DepartmentNotFoundException d) {
        throw new DepartmentNotFoundException("Department not found for Id: " + deptNo);
    }
}

package com.employeesService.EmployeesService.exception;

    public class DepartmentNotFoundException extends RuntimeException {

    public DepartmentNotFoundException(String msg) {
        super(msg);
    }

}


package com.employeesService.EmployeesService.exception;

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 java.time.ZoneId;
import java.time.ZonedDateTime;

@RestControllerAdvice
public class DepartmentExceptionHandler {

    @ExceptionHandler(value = {DepartmentNotFoundException.class})
    public ResponseEntity<Object> handleDepartmentException(DepartmentNotFoundException d) {
        HttpStatus notFound = HttpStatus.NOT_FOUND;

        DepartmentException departmentException = new DepartmentException(
                d.getMessage(),
                d,
                notFound,
                ZonedDateTime.now(ZoneId.of("Z"))
        );
        return new ResponseEntity<>(departmentException, notFound);
    }
}


   

package com.employeesService.EmployeesService.exception;

import org.springframework.http.HttpStatus;
import java.time.ZonedDateTime;

public class DepartmentException {
    private final String message;
    private final Throwable throwable;
    private final HttpStatus status;
    private final ZonedDateTime zonedDateTime;

    public DepartmentException(String message, Throwable throwable, HttpStatus status, ZonedDateTime zonedDateTime){
        this.message=message;
        this.throwable=throwable;
        this.status=status;
        this.zonedDateTime=zonedDateTime;
    }

    public String getMessage() {
        return message;
    }

    public Throwable getThrowable() {
        return throwable;
    }

    public HttpStatus getStatus() {
        return status;
    }

    public ZonedDateTime getZonedDateTime() {
        return zonedDateTime;
    }
}
2
  • You can create classes (e.g. DepartmentNotFoundException) that extends RuntimeException, and annotate them with @ResponseStatus(code = HttpStatus.NOT_FOUND). If optional.isPresent() is false, throw this exception. Commented Oct 13, 2021 at 16:08
  • I found the solution, thanks yall :) Commented Oct 14, 2021 at 22:34

1 Answer 1

1

try this:

@ExceptionHandler(value = {DepartmentNotFoundException.class})
public DepartmentException handleDepartmentException(DepartmentNotFoundException d, HttpServletResponse response) { // response will be automatically injected by spring
    HttpStatus notFound = HttpStatus.NOT_FOUND;

    DepartmentException departmentException = new DepartmentException(
            d.getMessage(),
            d,
            notFound,
            ZonedDateTime.now(ZoneId.of("Z"))
    );
    response.setStatus(notFound); // just do that here
    return departmentException;
}

PS: i would not return exceptions from my ExceptionHandler, a better solution is to define an ErrorObject (with some description / code about the error) and translate all your runtimeException into that object. Error class could look like that

public class Error {
  String code;
  String description;
  // any other useful properties
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.