Spring Boot高级编程技巧_异常处理 - @RestController@RestController
在Spring Boot中,异常处理是非常重要的一部分。以下是一些高级编程技巧:
@ControllerAdvice@ControllerAdvice
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public String handleGlobalException(Exception ex) {
return "全局异常处理";
}
}
@RestControllerAdvice@RestControllerAdvice
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@RestControllerAdvice
public class GlobalExceptionHandler {
@RequestMapping("/exception")
@ResponseBody
public String handleException() {
return "REST控制器全局异常处理";
}
}
自定义异常类:你可以创建一个自定义的异常类,然后在你的代码中使用这个异常类来表示特定的错误情况。例如:
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
@ControllerAdvice@ExceptionHandler@ControllerAdvice@ExceptionHandler
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
@ResponseBody
public String handleCustomException(CustomException ex) {
return "处理自定义异常:" + ex.getMessage();
}
}
@RestController@RestController
import org.springframework.boot.autoconfigure.rest.WebAutoConfigurationContext; 拼多多帮助力入口
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 添加资源处理器
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// 配置视图解析器
}
}
这些高级编程技巧可以帮助你更好地处理异常,提高代码的健壮性和可维护性。