java - Sprint Boot 中的自定义异常
问题描述
我在 SPRING BOOT 中编写了以下自定义错误处理程序
@RestControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler
// @ResponseBody
public ResponseEntity<CustomErrorResponse> customHandleNotFound(Exception ex, WebRequest request) {
CustomErrorResponse errors = new CustomErrorResponse();
errors.setTimestamp(LocalDateTime.now());
errors.setError(ex.getMessage());
errors.setStatus(HttpStatus.CONFLICT.value());
errors.setErrorMsg(errors.getErrorMsg());
return ResponseEntity.ok(errors);
}
下面是我的代码控制器方法
@RestController
@RequestMapping(value="/api")
public class AppController {
@Autowired
private UserRepository userRepository;
@RequestMapping(value="/home/{id1}" ,method=RequestMethod.PUT)
@ResponseBody
public String home(@PathVariable("id1") Long idValue, @RequestBody @Valid Student s)
{
System.out.println( " idValue is " + idValue);
System.out.println( " Student -->" + s.getName() + " -- " + s.getId());
return "job done";
}
@RequestMapping("/foos")
// @ResponseBody
public String getFoos(@RequestParam(value="t1",required=true) String id) {
int i =1/0;
System.out.println(" id is " + i++);
return "ID: " + id + " status: Success";
}
异常处理程序在遇到 1/0 时对方法 getFoos() 工作正常我得到 POSTMAN 中的输出,正如预期的那样
{
"timestamp": "2019-08-04 11:24:22",
"status": 409,
"error": "/ by zero",
"errorMsg": "ERROR-msg"
}
但是在我的 home() 方法中,我故意将 Student 对象设为无效,并且在 POSTMAN 中没有收到错误消息,而只是在 Eclipse 控制台中。为什么?
我收到此消息。那么当 Student 对象无效时如何启动 CustomGlobalExceptionHandler
2019-08-04 23:25:57.551 WARN 9652 --- [nio-8080-exec-6] .mmaExceptionHandlerExceptionResolver:已解决 [org.springframework.http.converter.HttpMessageNotReadableException:缺少所需的请求正文:公共 java.lang。字符串 com.example.hibernatemapping.controller.AppController.home(java.lang.Long,com.example.hibernatemapping.domain.Student)]
解决方案
我通过在我的 ControllerAdvice 中添加以下内容来解决它我只需更改代码以将错误映射到我的自定义 Pojo 类 CustomErrorResponse
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("status", status.value());
//Get all errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
System.out.println( " erro here ");
return new ResponseEntity<>(body, headers, status);
}
推荐阅读
- excel - 如何在 VBA 中重复此功能?
- javascript - 从对象列表创建属性数组
- mysql - MySQL 表问题
- javascript - HTML web IOS App日历未打开ical
- mysql - mysql视图如何自动更新
- qt - Qt Creator 导入的资产未显示
- vaadin-flow - Vaadin Flow:返回视图,视图不应从后端重新加载数据
- spring-boot - 使用 SpringBoot、NodeJS 和 Vue-CLI - 不保存会话
- ssl - STM32Cube_FW_F7 SSL 客户端 mbedTLS FATAL_ALERT
- python - 应用程序版本控制:如何处理密钥演变?