【发布时间】:2017-10-09 13:12:33
【问题描述】:
我想实现@PathVariable 验证,因此我为所有带有异常处理程序的控制器创建了一个基类:
public class BaseController {
@ExceptionHandler(value = { ConstraintViolationException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public RestError handleResourceNotFoundException(ConstraintViolationException e) {
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
StringBuilder strBuilder = new StringBuilder();
for (ConstraintViolation<?> violation : violations ) {
strBuilder.append(violation.getMessage());
strBuilder.append("\n");
}
strBuilder.deleteCharAt(strBuilder.lastIndexOf("\n"));
return new RestError(strBuilder.toString());
}
}
在扩展 BaseController 的控制器中,以下方法签名按预期工作(返回 {"error": invalid id}):
@PreAuthorize("hasRole('ROLE_VISA_ADMIN')")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
ResponseEntity<UserRepresentation> getUser(@Pattern(regexp = Constants.UUID_REGEX, message = "invalid id")
@PathVariable String id
而没有@PreAuthorize 的相同方法返回状态码500 和消息:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException. 好像没有异常处理程序一样。
我是 Spring Boot 的新手,所以任何建议都将受到高度赞赏。
编辑。
这是控制器的源代码(它实际上实现了描述api的接口):
@RestController
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class UserController extends BaseController implements UserApi {
private IUserService userService;
@Override
public ResponseEntity<UserRepresentation> getUser(@PathVariable String id) {
UserRepresentation userRepresentation = userService.getUserRepresentationById(id);
if (userRepresentation == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else {
return new ResponseEntity<>(userRepresentation, HttpStatus.OK);
}
}
}
【问题讨论】:
-
你能放一个完整的控制器来扩展
BaseController源代码吗? -
另见这里有一些非常有用的信息:stackoverflow.com/a/40346507/3635454
标签: java spring spring-boot