MST
星途 面试题库

面试题:Kotlin中如何在Spring Boot项目里优雅地处理异常

在Kotlin与Spring Boot整合开发的项目中,阐述如何自定义全局异常处理器来处理不同类型的异常,例如业务异常、参数校验异常等,并给出相应的代码示例。
16.8万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

1. 创建自定义异常类

在Kotlin中,首先定义业务异常类和参数校验异常类。

// 业务异常类
class BusinessException(message: String) : RuntimeException(message)

// 参数校验异常类
class ParameterValidationException(message: String) : RuntimeException(message)

2. 创建全局异常处理器

使用@ControllerAdvice注解来创建全局异常处理器,处理不同类型的异常。

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
class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException::class)
    fun handleBusinessException(ex: BusinessException): ResponseEntity<String> {
        return ResponseEntity(ex.message, HttpStatus.BAD_REQUEST)
    }

    @ExceptionHandler(ParameterValidationException::class)
    fun handleParameterValidationException(ex: ParameterValidationException): ResponseEntity<String> {
        return ResponseEntity(ex.message, HttpStatus.UNPROCESSABLE_ENTITY)
    }
}

在上述代码中:

  • @ControllerAdvice注解表明这是一个全局的异常处理组件。
  • @ExceptionHandler注解指定了具体处理的异常类型。当对应的异常抛出时,会执行相应的方法,并返回包含异常信息和对应HTTP状态码的响应。

3. 使用示例

在Controller中抛出这些异常来测试全局异常处理器。

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@RestController
class ExampleController {

    @GetMapping("/example")
    fun exampleMethod(@RequestParam value: String) {
        if (value.isEmpty()) {
            throw ParameterValidationException("参数不能为空")
        }
        if (value.length < 5) {
            throw BusinessException("业务逻辑要求参数长度至少为5")
        }
        // 正常业务逻辑
    }
}

在这个示例中,exampleMethod方法接收一个请求参数。如果参数为空,抛出ParameterValidationException;如果参数长度小于5,抛出BusinessException,然后全局异常处理器会捕获并处理这些异常。