1. Introduction
Restful Programming is the most popular practice in the current work environment. Sometimes, errors in the backend may cause frontend browsers to crash or be confused. Therefore, as professional and easy-to-work-with backend programmers, we need to handle our exceptions properly and let our frontend buddies understand what happened. This tutorial will use easy and simple examples to demonstrate the principle of exception handling in Java Restful Programming.
2. Example
Let's assume that we have a simple program that has a "Userbean" object with attributes of name and email, like the code below (let's pretend it is connected with a database):
public class UserBean {
private String name;
private String email;
//we also need all the getter and setter methods, with non-arg and normal constructor
...
}
Then, we have a controller response for connecting this bean with HTML pages;
@RestController
@RequestMapping("/demo")
public class RestfulDemoController {
@GetMapping("/normal")
public UserBean normalSituation(String name){
List<UserBean> list = new ArrayList<>();
list.add(new UserBean("Tom","tom@gmail.com"));
list.add(new UserBean("Maria","maria@gmail.com"));
list.add(new UserBean("Susan","susan@gmail.com"));
for(UserBean user : list){
if(user.getName().equals(name)){
return user;
}
}
throw new RuntimeException();
}
}
In this scenario, we used ajax on our frontend HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="showResult"></div>
</body>
<script>
let resultP = document.getElementById('showResult')
axios.get('normal',{
name:'Tom'
}).then(response => {
console.log(response)
})
</script>
</html>
After all this preparation, we will now formally start our procession. As codes in the controller are already displayed, an exception will be thrown out if we can not find a user with name searching in browsers.
However, this error message is very confusing and hard to read. So, what if we could send a simple Error Entity instead?
3. Custome Exception Handling
The first step in our customer exception handling is to create our exception class. To make the function clear, we called it "UserNotFoundException." This exception will extend RuntimeException and overrides some common method.
public class UserNotFoundException extends RuntimeException{
public UserNotFoundException(String message) {
super(message);
}
public UserNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public UserNotFoundException(Throwable cause) {
super(cause);
}
}
The second step is to create our special response. This response will be converted to JSON format once the not found exception is thrown out.
public class UserNotFoundException extends RuntimeException{
public UserNotFoundException(String message) {
super(message);
}
public UserNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public UserNotFoundException(Throwable cause) {
super(cause);
}
}
You can define your message; here is just an example.
Last but not least, we must establish an advice system for our program to capture all exceptions and convert them to the message we want. This step combines the AOP technique.
However, it is not intimidating but pretty easy to use, in fact.
@ControllerAdvice
public class CustomerExceptionHandler {
@ExceptionHandler
public ResponseEntity<MyErrorResponse> handleException(UserNotFoundException e){
MyErrorResponse response = new MyErrorResponse(HttpStatus.BAD_REQUEST.value(), "User is not found!",System.currentTimeMillis());
return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
}
}
The parameter needs to be our own "UserNotFoundException"; otherwise, it will catch all other exceptions. Meanwhile, two annotations (@ControllerAdvice and @ExceptionHandler) are necessary. Ok, finally, it is time to check out our results.
Congratulations! You just created your own not found error message!
4. Conclusion
we need to handle our exceptions properly and let our frontend buddies understand what happened in Restful Programming. The crucial idea is to create our exception response entity and use the AOP technique to capture exceptions and convert them to the message we want.