2

How to handle exception handling in Spring Boot 1.5.4 without controller class? Currently, I have only entity & repository class as below.

Task.class: (entity)

@Entity
@Table(name = "task")
public class Task implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    @Length(min = 1)
    private String name;

    public Task() {

    }

    public Task(String name) {
        this.name = name;
    }

    public Task(Long id, String name) {
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public String getName(){
        return name;
    }

}

Repository.class:

public interface TaskRepository extends PagingAndSortingRepository<Task, Long> {
}

POST method: return 200 ok

http://localhost:8080/tasks

{
"name" : "test"
}

But,

{
"name" : ""
}

returns 500 , instead of 400 error.

Pls let me know, if any way to handle this exception without a controller class.

1 Answer 1

3

You could use a global @ExceptionHandler with the @ControllerAdvice annotation. Basically, you define which Exception to handle with @ExceptionHandler within the class with @ControllerAdvice annotation, and then you implement what you want to do when that exception is thrown.

Like this:

@ControllerAdvice(basePackageClasses = RepositoryRestExceptionHandler.class)
public class GlobalExceptionHandler {

    @ExceptionHandler({ValidationException.class, JsonParseException.class})
    public ResponseEntity<Map<String, String>> yourExceptionHandler(Exception e) {
        Map<String, String> response = new HashMap<String, String>();
        response.put("message", "Bad Request");
        return new ResponseEntity<Map<String, String>>(response, HttpStatus.BAD_REQUEST);
    }
}

See also: http://www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html

Sign up to request clarification or add additional context in comments.

4 Comments

I do not have any controller class in my app. So, @ControllerAdvice annotation will work ?
Thanks... i have added exception classes and now able to see 404 error. But, how to get correct error code as 400 for my below request ? Scenario: empty string, string without quotes, empty body { "name" : "" } { "name" : test } { }
I was able to reproduce the error here and I saw that the exception was a ConstraintViolationException, which is a ValidationException... So I updated my answer to ValidationException... Check it out
And for the "{}" case, you need to add @NotBlank on name (Task class)

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.