我正在投注网站上,所以交易非常重要。
我使用@ControllerAdvice
创建了一个ExceptionHandler来捕获业务层中的所有异常。
@ControllerAdvice
public class HttpExceptionHandler {
private String getStackTrace(final Throwable throwable) {
final StringWriter stringWriter = new StringWriter()
final PrintWriter printWriter = new PrintWriter(stringWriter, true)
throwable.printStackTrace(printWriter)
stringWriter.getBuffer().toString()
}
private List<String> filterStackTrace(final String stackTrace) {
def stack = stackTrace.split('\n\t')
stack.findAll({ it.contains('com.dsindigo.trading') })
}
private ResponseEntity<HttpErrorResponse> buildResponse(final Exception ex, final String message) {
HttpErrorResponse error = new HttpErrorResponse(
stack: filterStackTrace(getStackTrace(ex)),
message: message
)
new ResponseEntity<HttpErrorResponse>(error, HttpStatus.BAD_REQUEST)
}
@ExceptionHandler(UsernameAlreadyExistsException)
ResponseEntity<HttpErrorResponse> catchUsernameAlreadyExists(final UsernameAlreadyExistsException ex) {
buildResponse(ex, HttpErrorMessages.USERNAME_ALREADY_EXISTS)
}
@ExceptionHandler(EmailAlreadyExistsException)
ResponseEntity<HttpErrorResponse> catchEmailAlreadyExists(final EmailAlreadyExistsException ex) {
buildResponse(ex, HttpErrorMessages.EMAIL_ALREADY_EXISTS)
}
//More exceptions...
@ExceptionHandler(Exception)
ResponseEntity<HttpErrorResponse> catchAny(final Exception ex) {
buildResponse(ex, HttpErrorMessages.UNKNOWN)
}
}
因此,基本上,它捕获异常(例如UsernameAlreadyExistsException
)并创建一个包含自定义消息和stacktrace的JSON响应(用于调试)。
这是服务引发自定义异常的示例:
@Service
class UserServiceImpl implements UserService {
// @Autowired stuff ...
@Override
@Transactional
UserDTO save(UserDTO user) {
UserDTO current = findOneByUsername(user.username)
if (current != null)
throw new UsernameAlreadyExistsException()
current = findOneByEmail(user.email)
if (current != null)
throw new EmailAlreadyExistsException()
ConfigurationDTO configuration = configurationService.findOne();
user.active = false
user.password = bCryptPasswordEncoder.encode(user.password)
user.balance = configuration.initialBalance
User entity = mapper.map(user, User)
entity = userRepository.save(entity)
user = mapper.map(entity, UserDTO)
transactionService.createForUser(user.id, INITIAL_CHIPS_ID, configuration.initialBalance)
TokenDTO token = tokenService.createForUser(user.id)
emailService.sendRegisterMessage(user.email, token.token)
user
}
}
问题是,当我抛出不带@Transactional
的自定义异常时,异常处理程序将执行正确的方法,而添加@Transactional
则将始终执行常规的Exception
方法。
我想念什么吗?
答案 0 :(得分:1)
这些声明:
@ExceptionHandler(UsernameAlreadyExistsException)
应该是这样的:
@ExceptionHandler(UsernameAlreadyExistsException.class)
此外,请确保您的异常正在扩展RuntimeException。如果异常在代码中的其他任何地方(包括Spring的拦截器!)被捕获并处理,则ControllerAdvice将不会对其进行处理。