小编rho*_*ath的帖子

防止Spring Boot应用程序中的自定义异常的堆栈跟踪日志记录

Spring Boot(mvc)中是否有一种方法可以记录自定义异常并抛出它,而不会在日志文件中看到它的堆栈跟踪?但是对于任何其他异常仍然会看到堆栈跟踪.

很长的解释:

我正在使用spring boot创建一个简单的休息服务.我喜欢自定义异常,默认情况下日志中没有堆栈跟踪,并且使用基本异常详细信息(状态,错误,消息)创建了json响应.

问题是它根本没有创建日志条目,因此我必须手动执行此操作:

自定义例外

@ResponseStatus(value = HttpStatus.CONFLICT)
public class DuplicateFoundException extends RuntimeException {
    public DuplicateFoundException(String message) {
        super(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

抛出服务方法的异常(在@RestController中)

if (!voteDao.findByItemAndUser(item, voteDto.getUserId()).isEmpty()) {
    log.warn("... already voted ...");   //TODO: don't do this for every throw
    throw new DuplicateFoundException("... already voted ...");
}
Run Code Online (Sandbox Code Playgroud)

有更多的异常导致在每次抛出之前放置日志语句,这是一种我认为不好的方法.我已经尝试从服务方法中删除所有日志语句并创建了@ControlledAdvice,我将记录所有自定义异常并重新抛出它们,所以我仍然像以前一样得到好的json:

@ControllerAdvice
public class RestExceptionHandler {
    private static final Logger log = Logger.getLogger(RestExceptionHandler.class);

    @ExceptionHandler
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        if …
Run Code Online (Sandbox Code Playgroud)

java logging spring exception-handling spring-boot

16
推荐指数
4
解决办法
1万
查看次数

Spring 数据存储库将 null 作为 bytea 发送到 PostgreSQL 数据库

从 MySQL 切换到PostgreSQL 后,我发现我的 SQL 查询(spring 数据存储库界面中的 @Query)不再起作用。该问题是由作为bytea发送的值引起的,我收到以下异常:

Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint = bytea
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
Run Code Online (Sandbox Code Playgroud)

带有@Query 的存储库:

public interface WineRepository extends PagingAndSortingRepository<Wine, Long> {
    @Query(value = "SELECT * FROM WINE w WHERE (?1 IS NULL OR w.id = ?1)", nativeQuery = true)
    Wine simpleTest(Long id);
}
Run Code Online (Sandbox Code Playgroud)

简单测试:

LOGGER.warn("test1: {}", wineRepository.simpleTest(1L));    //ok
LOGGER.warn("test2: …
Run Code Online (Sandbox Code Playgroud)

java postgresql hibernate spring-data spring-data-jpa

13
推荐指数
2
解决办法
3074
查看次数