【发布时间】:2018-04-24 18:36:47
【问题描述】:
我是弹簧和弹簧靴的新手。在创建了一个简单的 REST API 来对用户执行 CRUD 操作之后,我还创建了自定义异常处理程序来捕获应用程序中发生的任何异常。这是我写的代码
控制器类
public class UserController {
@Autowired
private IUserService userService;
@ApiOperation(value = "View list of all users", response = Iterable.class)
@RequestMapping(value = "/users", method = RequestMethod.GET)
public @ResponseBody List<User> getAll() throws EntityNotFoundException {
return userService.query();
}
@ApiOperation(value = "View a specific user", response = User.class)
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody List<User> getUser(@PathVariable(value = "id") String userid) throws EntityNotFoundException {
return userService.query(userid);
}
@ApiOperation(value = "create a user")
@RequestMapping(value = "/users", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<HttpStatus> createUser(@Valid @RequestBody User user) throws Exception {
userService.add(user);
return ResponseEntity.ok(HttpStatus.OK);
}
@ApiOperation(value = "update a user")
@RequestMapping(value = "/users", method = RequestMethod.PUT, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<User> updateUser(@Valid @RequestBody User entity) throws Exception {
User user = userService.update(entity);
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
}
@ApiOperation(value = "delete a user")
@RequestMapping(value = "/userid/{id}", method = RequestMethod.DELETE, produces = {
MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<HttpStatus> deleteUser(@PathVariable(value = "id") String userid) throws Exception {
String result = userService.remove(userid);
if (result.equals(null)) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(HttpStatus.OK);
}
}
使用@Controlleradvice 注释类的异常处理程序
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
/**
* Handles javax.validation.ConstraintViolationException. Thrown
* when @Validated fails.
*
* @param ex
* the ConstraintViolationException
* @return the ApiError object
*/
@ExceptionHandler(javax.validation.ConstraintViolationException.class)
protected ResponseEntity<Object> handleConstraintViolation(javax.validation.ConstraintViolationException ex) {
ApiError apiError = new ApiError(BAD_REQUEST);
apiError.setMessage("Validation error");
return buildResponseEntity(apiError);
}
/**
* Handles EntityNotFoundException. Created to encapsulate errors with more
* detail than javax.persistence.EntityNotFoundException.
*
* @param ex
* the EntityNotFoundException
* @return the ApiError object
*/
@ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<Object> handleEntityNotFound(EntityNotFoundException ex) {
ApiError apiError = new ApiError(NOT_FOUND);
apiError.setMessage(ex.getMessage());
return buildResponseEntity(apiError);
}
/**
* Handle Exception, handle generic Exception.class
*
* @param ex
* the Exception
* @return the ApiError object
*/
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex,
WebRequest request) {
ApiError apiError = new ApiError(BAD_REQUEST);
apiError.setMessage(String.format("The parameter '%s' of value '%s' could not be converted to type '%s'",
ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName()));
apiError.setDebugMessage(ex.getMessage());
return buildResponseEntity(apiError);
}
private ResponseEntity<Object> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, apiError.getStatus());
}
}
但是,当发生任何异常时,应用程序将被重定向到 /error 页面,而不是由异常处理程序类处理。任何人都可以就这样做的正确方法提出建议。
【问题讨论】:
标签: java spring spring-boot