Exception Handling in Java Restful Programming

本文介绍了在Java Restful编程中如何优雅地处理异常,确保前端能够理解错误信息。通过创建自定义异常类,定制错误响应,并使用AOP技术捕获并转换异常,简化错误信息,提供友好的错误消息给前端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值