001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.socket.messaging; 018 019import org.springframework.lang.Nullable; 020import org.springframework.messaging.Message; 021import org.springframework.messaging.simp.stomp.StompCommand; 022import org.springframework.messaging.simp.stomp.StompHeaderAccessor; 023import org.springframework.messaging.support.MessageBuilder; 024import org.springframework.messaging.support.MessageHeaderAccessor; 025import org.springframework.util.Assert; 026 027/** 028 * A {@link SubProtocolErrorHandler} for use with STOMP. 029 * 030 * @author Rossen Stoyanchev 031 * @since 4.2 032 */ 033public class StompSubProtocolErrorHandler implements SubProtocolErrorHandler<byte[]> { 034 035 private static final byte[] EMPTY_PAYLOAD = new byte[0]; 036 037 038 @Override 039 @Nullable 040 public Message<byte[]> handleClientMessageProcessingError(@Nullable Message<byte[]> clientMessage, Throwable ex) { 041 StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR); 042 accessor.setMessage(ex.getMessage()); 043 accessor.setLeaveMutable(true); 044 045 StompHeaderAccessor clientHeaderAccessor = null; 046 if (clientMessage != null) { 047 clientHeaderAccessor = MessageHeaderAccessor.getAccessor(clientMessage, StompHeaderAccessor.class); 048 if (clientHeaderAccessor != null) { 049 String receiptId = clientHeaderAccessor.getReceipt(); 050 if (receiptId != null) { 051 accessor.setReceiptId(receiptId); 052 } 053 } 054 } 055 056 return handleInternal(accessor, EMPTY_PAYLOAD, ex, clientHeaderAccessor); 057 } 058 059 @Override 060 @Nullable 061 public Message<byte[]> handleErrorMessageToClient(Message<byte[]> errorMessage) { 062 StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(errorMessage, StompHeaderAccessor.class); 063 Assert.notNull(accessor, "No StompHeaderAccessor"); 064 if (!accessor.isMutable()) { 065 accessor = StompHeaderAccessor.wrap(errorMessage); 066 } 067 return handleInternal(accessor, errorMessage.getPayload(), null, null); 068 } 069 070 protected Message<byte[]> handleInternal(StompHeaderAccessor errorHeaderAccessor, byte[] errorPayload, 071 @Nullable Throwable cause, @Nullable StompHeaderAccessor clientHeaderAccessor) { 072 073 return MessageBuilder.createMessage(errorPayload, errorHeaderAccessor.getMessageHeaders()); 074 } 075 076}