MST

星途 面试题库

面试题:Java中RESTful API异常处理之基础

在Java的RESTful API开发中,常见的异常类型有哪些?请至少列举3种,并说明如何使用Spring框架的`@ControllerAdvice`和`@ExceptionHandler`注解来处理这些异常,提供简单示例代码。
28.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 常见异常类型
    • NotFoundException:通常用于表示请求的资源不存在,比如在根据ID查询数据库记录,而该ID对应的记录不存在时可以抛出此异常。
    • BadRequestException:表示客户端发送的请求有误,比如请求参数格式不正确等情况。
    • UnauthorizedException:当用户未经过身份验证,尝试访问需要授权的资源时抛出。
  2. 使用@ControllerAdvice@ExceptionHandler注解处理异常示例代码
    • 首先创建一个全局异常处理类:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NotFoundException.class)
    public ResponseEntity<String> handleNotFoundException(NotFoundException ex) {
        return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(BadRequestException.class)
    public ResponseEntity<String> handleBadRequestException(BadRequestException ex) {
        return new ResponseEntity<>("Bad request", HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity<String> handleUnauthorizedException(UnauthorizedException ex) {
        return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
    }
}
  • 然后在实际业务代码中可以抛出这些异常,例如:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExampleController {

    @GetMapping("/example/{id}")
    public String getExample(@PathVariable Long id) {
        if (id < 0) {
            throw new BadRequestException();
        }
        // 模拟查询数据库,如果没找到则抛出NotFoundException
        boolean exists = false;
        if (!exists) {
            throw new NotFoundException();
        }
        // 如果需要身份验证,未通过验证可抛出UnauthorizedException
        boolean isAuthenticated = false;
        if (!isAuthenticated) {
            throw new UnauthorizedException();
        }
        return "Example response";
    }
}
  • 自定义异常类示例:
public class NotFoundException extends RuntimeException {
    public NotFoundException() {
        super();
    }

    public NotFoundException(String message) {
        super(message);
    }
}

public class BadRequestException extends RuntimeException {
    public BadRequestException() {
        super();
    }

    public BadRequestException(String message) {
        super(message);
    }
}

public class UnauthorizedException extends RuntimeException {
    public UnauthorizedException() {
        super();
    }

    public UnauthorizedException(String message) {
        super(message);
    }
}