Taulant Fazliu
Taulant Fazliu

Reputation: 73

how to map a custom exception with HTTP 404 status code

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;
    }
}

Upvotes: 2

Views: 1483

Answers (1)

Djebarri Amazigh
Djebarri Amazigh

Reputation: 219

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
}

Upvotes: 1

Related Questions