1
1
.
.
1
1
.
.
7
7
T
T
h
h
r
r
o
o
w
w
E
E
x
x
c
c
e
e
p
p
t
t
i
i
o
o
n
n
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to catch Validation Exceptions by adding @ExceptionHandler Methods to the Controller.
Such Methods can only catch Exceptions thrown inside the same Controller.
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
hello()
MyController
http://localhost:8080/Hello
Browser
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_validation_catchexception_eceptionhandler (add Spring Boot Starters from the table)
Edit File: pom.xml (add validation dependency)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation </artifactId>
</dependency>
MyController.java
package com.ivoronline.springboot_validation_exception_throw.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
@Controller
@Validated
public class MyController {
//==================================================================
// HELLO
//==================================================================
@ResponseBody
@RequestMapping("/Hello")
public void hello() {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "There was some Exception");
}
//==================================================================
// HANDLE EXCEPTIONS
//==================================================================
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ResponseStatusException.class)
public String handleExceptions(ResponseStatusException exception) {
//GET EXCEPTION DETAILS
String message = exception.getMessage(); //400 BAD_REQUEST "There was some Exception"
HttpStatus status = exception.getStatus(); //400 BAD_REQUEST
String reason = exception.getReason(); //There was some Exception
Integer statusValue = status.value(); //400
String statusPhrase = status.getReasonPhrase(); //Bad Request
//RETURN MESSAGE
return message;
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/Hello (reports only first error)
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>